Array findLast / findLastIndexLoading saved progress…

Array findLast / findLastIndex

findLast and findLastIndex search an array from the end: findLast returns the last element that satisfies a test function, and findLastIndex returns that element's index. They are the mirror image of find and findIndex, which scan from the front and return the first match. Reaching for findLast is how you get the most recent matching item in a list kept in order, without copying or reversing it first. See the MDN reference.

Implement both as standalone functions that scan from the last index toward the first. Do not call the real Array.prototype methods.

Signature

findLast(arr, predicate)      // the last element where predicate is truthy, or undefined
findLastIndex(arr, predicate) // the index of that element, or -1
// predicate(element, index, array) — same shape as Array.prototype.find

Examples

findLast([1, 2, 3, 4], (n) => n % 2 === 0);      // 4  — the last even number
findLastIndex([1, 2, 3, 4], (n) => n % 2 === 0); // 3  — its index
findLast([1, 3, 5], (n) => n % 2 === 0);         // undefined — nothing matches
findLastIndex([1, 3, 5], (n) => n % 2 === 0);    // -1

Notes

  • Scan from the end — walk from the last index toward 0 and stop at the first match; that element is the last match in array order.
  • Predicate shape — the predicate is called with (element, index, array), exactly like the callback for find. The index is the element's real position, even though the scan runs backward.
  • Two not-found sentinelsfindLast returns undefined; findLastIndex returns -1. Do not mix them up.
  • Do not mutate — you are only reading; the input array must read the same after the call.
  • Do not use the built-ins — write the scan yourself; do not call the real Array.prototype.findLast or findLastIndex.

FAQ

What is the difference between find and findLast?
find scans the array from the start and returns the first element that matches; findLast scans from the end and returns the last one. When several elements match, they return opposite ends of the array.
What do findLast and findLastIndex return when nothing matches?
findLast returns undefined and findLastIndex returns -1, mirroring find and findIndex. The index sentinel is -1, never undefined, so callers can test the result with === -1.
What arguments does the predicate receive?
It is called with (element, index, array) for each element visited, exactly like the callback passed to find. The index is the element's real position in the original array, even though the scan runs backward.
Loading editor…