JS Built-ins
← Array81 / 226
ArrayArray.prototype.findLastintermediate

Array.prototype.findLast() β€” first vs last match

πŸ“– Usage Example
const nums = [1, 3, 5, 2, 4]
nums.find(n => n % 2 === 0)      // β†’ 2  (first even)
nums.findLast(n => n % 2 === 0)  // β†’ 4  (last even)

Use findLast() instead of find() when you need the last matching element rather than the first.

Array.prototype.findLast() β€” comparing with find()

The difference between find() and findLast() becomes clear when the predicate matches multiple elements. find() returns the first; findLast() returns the last.

Challenge: Implement firstVsLast(nums, pred) that returns a tuple [find result, findLast result].

firstVsLast([1, 2, 3, 4, 5], n => n % 2 === 0) // β†’ [2, 4]
πŸ’‘ Hints (2)
  • β€’ `find()` returns the first match scanning left to right.
  • β€’ `findLast()` returns the last match scanning right to left.