Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mutate original array in Javascript .map() function?

Tags:

javascript

For eg:

var persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary":"1500" }];

And you want to change the value of "salary" of each person in an original array.

like image 259
Maxgrid Avatar asked Oct 02 '17 07:10

Maxgrid


People also ask

Does map mutate the original array?

map does not mutate the array on which it is called (although callbackFn , if invoked, may do so). The range of elements processed by map is set before the first invocation of callbackFn .

How do you update an array on a map?

To update all the elements in an array:Call the map() method to iterate over the array. On each iteration, return the updated value. The map() method will return a new array that contains the updated values.

Can you mutate an array?

Arrays in JavaScript are just objects, which means they can be mutated. In fact, many of the built-in array methods will mutate the array itself.


Video Answer


3 Answers

If you want to mutate the original array, you can use Array#forEach function.

const persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary": 1500 }];

persons.forEach(item => item.salary += 1000);

console.log(persons)

Array#map creates a new array of the created items and returns that. After you need to assign the returned result.

let persons = [{ "name":"A", "salary":1200 }, { "name":"B", "salary": 1500 }];

persons = persons.map(item => {
  item.salary += 1000;
  return item;
});

console.log(persons);
like image 190
Suren Srapyan Avatar answered Oct 17 '22 02:10

Suren Srapyan


You can mutate the objects directly iterating with map. If I understood you correctly.

persons.map(i => { i.salary = i.salary * 1.25; return i; });
console.log(persons);
// [{ "name":"A", "salary": 1875 }, { "name":"B", "salary": 2343.75 }]

Though it's anti-pattern and you should avoid performing mutations of your original array in map().

like image 24
terreb Avatar answered Oct 17 '22 02:10

terreb


Use forEach. If your array is full of objects, and you simply want to mutate those objects — like in the original question — then you can simply have your callback function mutate the item passed to it in its first argument.

If your array is full of primitives, which can only be changed by assigning something else to the array slots, thereby mutating the array — or if for some other reason you want to reassign things to the array slots — you can still use forEach. The second parameter and third parameters passed to the callback are the array index of the element currently being operated on, and a reference to the array itself. So within the callback function, you can assign to the relevant array slot.

like image 2
Maggie David Haynes Avatar answered Oct 17 '22 01:10

Maggie David Haynes