javascriptarraysecmascript-6immutability

Replace element at specific position in an array without mutating it


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?


Solution

  • You can use Object.assign(target, source1, source2, /* …, */ sourceN):

    Object.assign([], array, {2: newItem});