JS Built-ins
← Array42 / 226
ArrayArray.prototype.copyWithinintermediate

Array.prototype.copyWithin() β€” copy to index

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

Use copyWithin(target, start) to copy part of an array to another position within the same array.

Array.prototype.copyWithin()

Array.prototype.copyWithin(target, start, end) copies a portion of the array to another location within the same array and returns it. The array's length is unchanged, and the operation mutates the original array.

Challenge: Implement copyFirst(arr) that copies the element at index 0 to index 2 using arr.copyWithin(2, 0, 1).

copyFirst([1, 2, 3, 4, 5]) // β†’ [1, 2, 1, 4, 5]
copyFirst([9, 8, 7])       // β†’ [9, 8, 9]
πŸ’‘ Hints (2)
  • β€’ `copyWithin(target, start, end)`: copies elements from [start, end) to position target.
  • β€’ The end argument is exclusive, so `copyWithin(2, 0, 1)` copies only arr[0].