How can the following operation be done without mutating the array:
let array = ['item1'];
console.log(array); // ['item1']
array[2] = 'item2'; // array is mutated
console.log(array); // ['item1', undefined, 'item2']
In the above code, array
variable is mutated. How can I perform the same operation without mutating the array?
To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.
SPlice will mutate your original array. Slice won't mutate your original array.
You can use Object.assign
:
Object.assign([], array, {2: newItem});
function replaceAt(array, index, value) {
const ret = array.slice(0);
ret[index] = value;
return ret;
}
See the JSPerf (thanks to @Bless)
Related posts:
You can simply set up a new array as such:
const newItemArray = array.slice();
And then set value for the index which you wish to have a value for.
newItemArray[position] = newItem
and return that. The values under the indexes in-between will have undefined
.
Or the obviously alternative would be:
Object.assign([], array, {<position_here>: newItem});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With