JS Built-ins
← Array45 / 226
ArrayArray.prototype.copyWithinadvanced

Array.prototype.copyWithin() β€” copy a range

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.copyWithin(1, 3, 5)  // β†’ [1, 4, 5, 4, 5]
// copies slice [3,5) to position 1

Provide start and end arguments to copyWithin() to copy only a specific slice.

Array.prototype.copyWithin() β€” full parameter usage

With all three parameters (target, start, end), you can copy any slice of an array to any position within itself.

Challenge: Implement copyRange(arr, target, start, end) that wraps arr.copyWithin(target, start, end).

copyRange([1, 2, 3, 4, 5], 0, 3, 5) // β†’ [4, 5, 3, 4, 5]
copyRange([1, 2, 3, 4, 5], 1, 3)    // β†’ [1, 4, 5, 4, 5]
πŸ’‘ Hints (2)
  • β€’ `copyWithin(target, start, end)` β€” elements from [start, end) are written starting at target.
  • β€’ The `end` parameter is optional; if omitted it defaults to `arr.length`.