JS Built-ins
← Array82 / 226
ArrayArray.prototype.findLastIndexbeginner

Array.prototype.findLastIndex() β€” index of last even

πŸ“– Usage Example
const nums = [1, 3, 7, 2, 5]
nums.findLastIndex(n => n % 2 !== 0)  // β†’ 4  (index of last odd)

Use findLastIndex() to get the index of the last element satisfying a condition.

Array.prototype.findLastIndex()

Array.prototype.findLastIndex(callback) is the reverse of findIndex(). It iterates from the end and returns the index of the last element for which the callback is truthy, or -1 if not found.

Challenge: Implement lastEvenIndex(nums) that returns the index of the last even number.

lastEvenIndex([1, 2, 3, 4, 5]) // β†’ 3
lastEvenIndex([1, 3, 5])       // β†’ -1
πŸ’‘ Hints (2)
  • β€’ `findLastIndex()` returns the index of the last matching element, not the element itself.
  • β€’ Returns `-1` when no element satisfies the predicate.