Aniruddha Das
Aniruddha Das

Reputation: 21698

JavaScript Map, Filter, redule, forEach does not change the original array. right?

I have been using these array function and know that these does not change the original array. correct me if I am wrong.

And these function does not work on object.

Is there anything available in javascript which will change the original array. I know the work around is

arr = arr.map((val, index)=>{// change value here}); // I dont want to assign the aray it shelf

I want something like

arr.map((val, index)=>{// change value here}); // it should change the original array

Upvotes: 1

Views: 174

Answers (3)

Daniel A. White
Daniel A. White

Reputation: 190996

None of those methods have side effects to each element since everything in JavaScript is passed by value. You can modify the items themselves, just not what is referenced in the array.

If you really want to change the original array, a traditional for loop can do that or just use the index argument provided.

for (var i = 0; i <= arr.length; i++) {
  if (shouldReplace(i)) {
     arr[i] = newValue(i);
  }
}

Upvotes: 1

Corey
Corey

Reputation: 5818

The map callback method accepts a third parameter which is the original array. So you could technically do something like this:

var arr = ['apple', 'orange', 'banana', 'grape'];

arr.map((item, idx, org) => org[idx] = '1 ' + item);

console.log(arr);

Upvotes: 0

jamison
jamison

Reputation: 311

If you are not willing to re-assign the variable as you mentioned, and you are not adding or removing elements, then your best bet is:

arr.forEach((val, index)=>{val.foo = bar;});

Upvotes: 0

Related Questions