JS Built-ins
← Array61 / 226
ArrayArray.prototype.fillintermediate

Array.prototype.fill() β€” fill last elements with negative index

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.fill(0, -3)  // β†’ [1, 2, 0, 0, 0]
// fills the last 3 elements

Use a negative start index with fill() to fill elements counting from the end.

Array.prototype.fill() β€” negative start index

fill() supports negative indices for start and end. fill(val, -2) fills the last two elements of the array.

Challenge: Implement fillLastTwo(arr, val) that fills the last 2 elements of arr with val using arr.fill(val, -2).

fillLastTwo([1, 2, 3, 4, 5], 0) // β†’ [1, 2, 3, 0, 0]
fillLastTwo([10, 20], 99)       // β†’ [99, 99]
πŸ’‘ Hints (2)
  • β€’ Negative index `-2` means start from the 2nd element from the end.
  • β€’ For an array of length 5, `-2` maps to index `3` (i.e. `5 - 2`).