im a new blocked because I am learning
i want to remplace a value in array without knowing the position of each word (like tab[0]).
The problem is that you have to find a word, followed by another (search test and remplace test-blabla by another like newblabla
I thought about
array = ['test blabla', 'haha hihi']
let index = array.indexOf("test");
if (index !== -1) {
array[index] = newblabla;
}
console.log(index)
it return -1 because it's not 'test' its 'test blabla' but I would like that to be replaced 'test blabla' by 'newblabla'
how can i do that ?
Thanks
You are trying to find indexOf variable test, which is undefined.
let list = ['test blabla', 'haha hihi']
// here we are doing following things
// 1. We are mapping trough each item of an array
// 2. If item of an array is equals to 'test blabla' then replace it with 'newblabla'
// 3. If item is not equal to 'test blabla', return it without modifing
list = list.map(item => item === 'test blabla' ? 'newblabla' : item);
console.log(list);
You can use a simple map.
const arr = ['a', 'b', 'c']
// Replace 'b' by something else
const newArr = arr.map(v => (v === 'b' ? 'something else' : v))
console.log(newArr)
You can easily achive the result using map and replace
const array = ["test blabla", "haha hihi"];
function searchAndReplace(arr, text) {
return arr.map((str) => {
const splitArr = str.split(" ");
return splitArr[0] === text ? splitArr[1] : str;
});
}
console.log(searchAndReplace(array, "test"));