JS Built-ins
← Array124 / 226
ArrayArray.prototype.lastIndexOfintermediate

Array.prototype.lastIndexOf() β€” search from a given index

πŸ“– Usage Example
const arr = [1, 2, 3, 2, 1]
arr.lastIndexOf(2, 2)  // β†’ 1  (search backwards from index 2)

Pass a fromIndex to lastIndexOf() to limit how far back the backward search goes.

Array.prototype.lastIndexOf() β€” fromIndex

The optional second argument fromIndex tells lastIndexOf where to start searching backwards. Only positions ≀ fromIndex are considered.

Challenge: Implement lastPosFrom(arr, val, from) that uses arr.lastIndexOf(val, from).

lastPosFrom([1, 2, 3, 2, 1], 2, 2) // β†’ 1  (search up to index 2)
lastPosFrom([1, 2, 3, 2, 1], 2, 3) // β†’ 3
πŸ’‘ Hints (3)
  • β€’ `lastIndexOf(val, from)` starts the backward search at position `from`.
  • β€’ Positions after `from` are completely ignored.
  • β€’ If `from` is 0 and the value is not at index 0, the result is `-1`.