0

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.

3
  • Does this answer your question? How to replace item in array? Commented Mar 1, 2021 at 6:47
  • 2
    @gorak Not quite a duplicate, though logically similar. This question wants to replace all elements of an array that meet a condition, not just the first one, and the accepted answer simply mutates the array, something we typically avoid in React. Commented Mar 1, 2021 at 6:51
  • @DrewReese look at this answer in that question stackoverflow.com/a/5915891/10004893 Commented Mar 1, 2021 at 6:54

6 Answers 6

3

You would (should) need to map to a new array so you avoid array mutations.

["John", "John", "Herald", "John"].map(el => el === 'John' ? 'Margaret' : el);

const array = ["John", "John", "Herald", "John"].map(el => el === 'John' ? 'Margaret' : el);

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

1

const array = ["John", "John", "Herald", "John"]
array.forEach((element, index) => {
   if(element === 'John') {
      array[index] = 'Margaret';
   }
 });

console.log(array); // ["Margaret", "Margaret", "Herald", "Margaret"]

Comments

1

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"]

Comments

0
function replaceAll(arr, valueToReplace, replaceWith) {
  return arr.map(e => valueToReplace === e ? replaceWith : e)
}

1 Comment

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive feedback/upvotes from users, when the code is explained.
0

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

Comments

0

const names = ["John", "John", "Herald", "John"]
  .join(" ")
  .replace(/John/g, "Margaret")
  .split(" ");

console.log(names);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.