JS Built-ins
← Array126 / 226
ArrayArray.prototype.lastIndexOfadvanced

Array.prototype.lastIndexOf() β€” collect all occurrences

πŸ“– Usage Example
const arr = [1, 2, 1, 2, 1]
const indices = []
let i = arr.lastIndexOf(1)
while (i !== -1) { indices.push(i); i = arr.lastIndexOf(1, i - 1) }
// indices β†’ [4, 2, 0]

Use lastIndexOf() in a loop to collect all positions of a value, from last to first.

Array.prototype.lastIndexOf() β€” find all indices

By repeatedly calling lastIndexOf with a decreasing fromIndex, you can collect every index where a value appears β€” all without using filter or reduce.

Challenge: Implement allIndices(arr, val) that returns an array of all indices where val appears, in ascending order.

allIndices([1, 2, 1, 3, 1], 1) // β†’ [0, 2, 4]
allIndices([1, 2, 3], 9)       // β†’ []
πŸ’‘ Hints (4)
  • β€’ Start by calling `arr.lastIndexOf(val)` to find the rightmost index.
  • β€’ Next, call `arr.lastIndexOf(val, i - 1)` to search before that position.
  • β€’ Use `result.unshift(i)` to prepend each found index, so the final array is in ascending order.
  • β€’ Stop the loop when `lastIndexOf` returns `-1`.