Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 537
Bless Avatar asked Jun 27 '16 18:06

Bless


People also ask

How do you replace an element in an 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.

Does JavaScript splice mutate?

SPlice will mutate your original array. Slice won't mutate your original array.


3 Answers

You can use Object.assign:

Object.assign([], array, {2: newItem});
like image 185
Oriol Avatar answered Oct 18 '22 20:10

Oriol


The fast way

function replaceAt(array, index, value) {
  const ret = array.slice(0);
  ret[index] = value;
  return ret;
}

See the JSPerf (thanks to @Bless)

Related posts:

  • Javascript fastest way to duplicate an Array - slice vs for loop
  • https://github.com/lodash/lodash/issues/2053#issuecomment-188776090
like image 17
Yves M. Avatar answered Oct 18 '22 21:10

Yves M.


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});
like image 12
Elod Szopos Avatar answered Oct 18 '22 20:10

Elod Szopos