JS Built-ins
← Array186 / 226
ArrayArray.prototype.spliceadvanced

Array.prototype.splice() β€” replace a range

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.splice(1, 2, 10, 20, 30)  // replaces 2 with 3 values
arr  // β†’ [1, 10, 20, 30, 4, 5]

Use splice() to remove and insert any number of elements in a single operation.

Array.prototype.splice() β€” remove and insert multiple

You can remove multiple elements and insert multiple replacements in one splice call. The number of removed and inserted items do not need to match.

Challenge: Implement replaceRange(arr, start, count, ...items) that removes count elements from start and inserts items, then returns the mutated array.

replaceRange([1, 2, 3, 4, 5], 1, 2, 10, 20, 30)
// β†’ [1, 10, 20, 30, 4, 5]
πŸ’‘ Hints (2)
  • β€’ Spread `items` into `splice`: `arr.splice(start, count, ...items)`.
  • β€’ Rest parameters (`...items`) capture any number of trailing arguments as an array.