Find the index of the last matching item of an array
Scan from the end and return the first index whose item matches.
function lastIndex(values, predicate) { return values.findLastIndex(predicate); }
Usage
lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], n => n % 2 === 1); // → 4
lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], n => n > 6); // → 5
lastIndex([], () => true); // → -1
Know the limits
- Array.prototype.findLastIndex is ES2023: Node.js 18+ and current browsers. The original reduced the whole array; findLastIndex stops at the first match from the end.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Find the index of the last matching item of an array from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses Array.prototype.findLastIndex (ES2023). Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.