Given a JavaScript array, how can you modify the items in an array with the forEach
operator?
Asked
Active
Viewed 46 times
-2

J. Peterson
- 1,996
- 1
- 24
- 21
-
1See [is it possible to change values of the array when doing foreach in javascript?](https://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript) – p.s.w.g Feb 27 '19 at 23:53
2 Answers
1
This is a simple question, but I'm posting the answer so I don't have to figure it out from scratch again. The function called by forEach
takes three parameters, the current item, the index of that item, and the array object. So, using a =>
style function, the solution is:
var data = [1,2,3,4];
data.forEach( (item, i, self) => self[i] = item + 10 );
gives the result:
[11,12,13,14]
The self
parameter isn't strictly necessary with the arrow style function, so
data.forEach( (item,i) => data[i] = item + 10);
also works. You also get the same result using a regular function, e.g.:
data.forEach( function(item, i, self) { self[i] = item + 10; } );

J. Peterson
- 1,996
- 1
- 24
- 21
1
If you're replacing array items, a better way to do this is to use map
instead:
var data = [1, 2, 3, 4];
data = data.map(item => item + 10);

frodo2975
- 10,340
- 3
- 34
- 41
-
I think this would be the better approach in most scenarios, but the question seems to be about modifying the array in place (I didn't downvote though). – Carcigenicate Feb 28 '19 at 00:03
-
I agree that map would be better, but you should provide an example. Your answer as it stands is more of a comment than an answer. – richbai90 Feb 28 '19 at 00:06
-
That is true, I'll update it to add an example. It is true that there are rare cases where you might want to modify an array in place, but I would say that generally using a map is preferred because it's easier to read. – frodo2975 Feb 28 '19 at 00:07