Reputation: 21698
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
arr.map((val, index)=>{// change value here}); // it should change the original array
Upvotes: 1
Views: 174
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
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
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