Replace element at specific position in an array without mutating it

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});

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:

  • Javascript fastest way to duplicate an Array - slice vs for loop
  • https://github.com/lodash/lodash/issues/2053#issuecomment-188776090