JS Built-ins
← Array86 / 226
ArrayArray.prototype.findLastIndexadvanced

Array.prototype.findLastIndex() β€” last duplicate index

πŸ“– Usage Example
const logs = ['ok', 'error', 'ok', 'error']
logs.findLastIndex(l => l === 'error')  // β†’ 3

Use findLastIndex() when you need the index of the most recent occurrence of a condition.

Array.prototype.findLastIndex() β€” practical use case

findLastIndex() can be used to find the last element that meets a condition requiring knowledge of the whole array β€” like being a duplicate.

Challenge: Implement lastDuplicateIndex(arr) that returns the index of the last element that appears more than once.

lastDuplicateIndex([1, 2, 3, 2, 1]) // β†’ 4 (1 appears at 0 and 4)
lastDuplicateIndex([1, 2, 3])       // β†’ -1
πŸ’‘ Hints (2)
  • β€’ Inside `findLastIndex`, use `arr.some(...)` to check if the same value appears at a different index.
  • β€’ `findLastIndex` scans from the end, so the first match it finds is the last duplicate in the array.