Replace element at specific position in an array without mutating it Replace element at specific position in an array without mutating it arrays arrays

Replace element at specific position in an array without mutating it


You can use Object.assign:

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


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:


You can simply set up a 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});