soy un nuevo bloqueado porque estoy aprendiendo
quiero reemplazar un valor en la matriz sin saber la posición de cada palabra (como tab[0]).
El problema es que hay que buscar una palabra, seguida de otra (buscar test y sustituir test-blabla por otra como newblabla
Yo pense acerca de
array = ['test blabla', 'haha hihi'] let index = array.indexOf("test"); if (index !== -1) { array[index] = newblabla; } console.log(index)devuelve -1 porque no es 'test' es 'test blabla' pero me gustaría que se reemplace 'test blabla' por 'newblabla'
Cómo puedo hacer eso ?
Gracias
Está tratando de encontrar la prueba de la variable indexOf, que no está definida.
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);Puedes usar un mapa simple.
const arr = ['a', 'b', 'c'] // Replace 'b' by something else const newArr = arr.map(v => (v === 'b' ? 'something else' : v)) console.log(newArr)Puede lograr fácilmente el resultado usando el mapa y reemplazar
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"));