I want to replace all "John"s with "Margaret"s in following code:
array = ["John", "John", "Herald", "John"]
I have tried:
array[array.indexOf('John')] = 'Margaret', but that breaks.
I use React.js with TypeScript.
I want to replace all "John"s with "Margaret"s in following code:
array = ["John", "John", "Herald", "John"]
I have tried:
array[array.indexOf('John')] = 'Margaret', but that breaks.
I use React.js with TypeScript.
I personally would go with Drew Reese because it is a one liner and it is clean answer but if need a bit of elaboration please see below answer.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = ["John", "John", "Herald", "John"];
// pass a function to map
const map1 = array1.map(el => el === 'John' ? 'Margaret' : el);
console.log(map1);
// expected output: Array ["Margaret", "Margaret", "Herald", "Margaret"]
function replaceAll(arr, valueToReplace, replaceWith) {
return arr.map(e => valueToReplace === e ? replaceWith : e)
}
I think you should write a prototype for better reuse and input substitution.
Array.prototype.replaceAll = function(find, replace){
return this.map(function(item){
return item === find ? replace : item;
});
}
See at: https://i.sstatic.net/hHy41.png