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

Array.prototype.copyWithin() β€” shift elements left

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.copyWithin(0, 3)  // β†’ [4, 5, 3, 4, 5]
// pastes elements at index 3+ to the start

Pass 0 as the target to copyWithin() to shift elements to the beginning of the array.

Array.prototype.copyWithin() β€” shifting

Copying from index 1 to index 0 effectively shifts elements left by one position. The last element remains unchanged (since the source is one shorter than the target range).

Challenge: Implement shiftLeft(arr) that copies from index 1 to the beginning of the array using arr.copyWithin(0, 1).

shiftLeft([1, 2, 3, 4]) // β†’ [2, 3, 4, 4]
shiftLeft([10, 20, 30]) // β†’ [20, 30, 30]
πŸ’‘ Hints (2)
  • β€’ `copyWithin(0, 1)` copies arr[1], arr[2], arr[3]... to positions 0, 1, 2...
  • β€’ The last element stays because there is no element to copy into its position from the right.