JS Built-ins
← Array200 / 226
ArrayArray.prototype.toSplicedintermediate

Replace Element Immutably

πŸ“– Usage Example
const arr = ['a', 'b', 'c']
arr.toSpliced(1, 1, 'X')  // β†’ ['a', 'X', 'c']
arr  // β†’ ['a', 'b', 'c']  (unchanged)

Use toSpliced() to replace elements at a position, returning a new array.

Array.prototype.toSpliced β€” Replace

Combining a delete count of 1 with a replacement value lets you replace an element at a given index without mutating the original.

Implement replaceImmutable which returns a new array with the element at index replaced by val.

πŸ’‘ Hints (2)
  • β€’ Use toSpliced(index, 1, val) β€” remove 1 element at index and insert val in its place
  • β€’ The length of the result equals the length of the original