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

Insert Element Immutably

πŸ“– Usage Example
const arr = [1, 2, 4, 5]
arr.toSpliced(2, 0, 3)  // β†’ [1, 2, 3, 4, 5]
arr  // β†’ [1, 2, 4, 5]  (unchanged)

Use toSpliced() to insert elements at a position without modifying the original array.

Array.prototype.toSpliced β€” Insert

Passing 0 as the delete count lets you insert elements without removing any.

Implement insertImmutable which returns a new array with val inserted at index.

πŸ’‘ Hints (2)
  • β€’ Use toSpliced(index, 0, val) β€” deleteCount of 0 means nothing is removed
  • β€’ The new element appears at the given index in the returned array