JS Built-ins
← Array185 / 226
ArrayArray.prototype.spliceintermediate

Array.prototype.splice() β€” capture removed elements

πŸ“– Usage Example
const arr = [10, 20, 30, 40]
const removed = arr.splice(1, 2)  // β†’ [20, 30]
arr  // β†’ [10, 40]

splice() returns an array of the removed elements β€” capture it when you need those values.

Array.prototype.splice() β€” return value

splice returns an array of the removed elements. This is useful when you need to both remove and capture a range of values.

Challenge: Implement getRemovedElements(arr, start, count) that returns the array of removed elements (the return value of splice).

getRemovedElements([1, 2, 3, 4, 5], 1, 2) // β†’ [2, 3]
getRemovedElements([10, 20, 30], 0, 1)     // β†’ [10]
πŸ’‘ Hints (2)
  • β€’ `splice` returns an array even if only one element is removed.
  • β€’ The original array is modified β€” elements are actually taken out.