Back

How to Get the Last Matching Array Value in JavaScript

How to Get the Last Matching Array Value in JavaScript

You need to find the last element in an array that matches a condition. Maybe it’s the most recent error log, the final valid form input, or the last user who was active. Before ES2023, this meant awkward workarounds—reversing arrays, filtering everything, or writing manual loops. Now there’s a cleaner way.

Key Takeaways

  • Use findLast() to retrieve the last array element matching a condition without mutating the original array.
  • Use findLastIndex() when you need the position rather than the value itself.
  • Avoid using reverse().find() as it mutates the original array and introduces subtle bugs.
  • Remember the different return values: findLast() returns undefined when no match is found, while findLastIndex() returns -1.

The Modern Solution: Array.prototype.findLast()

Array.prototype.findLast() iterates backward through an array and returns the first element that satisfies your predicate. It’s the mirror of find(), which searches from the start.

const logs = [
  { type: 'info', message: 'Started' },
  { type: 'error', message: 'Connection failed' },
  { type: 'info', message: 'Retrying' },
  { type: 'error', message: 'Timeout' }
]

const lastError = logs.findLast(log => log.type === 'error')
// { type: 'error', message: 'Timeout' }

If no element matches, findLast() returns undefined. This makes it safe to use with optional chaining:

const lastError = logs.findLast(log => log.type === 'critical')?.message ?? 'No critical errors'

findLast vs findLastIndex: When You Need the Position

Sometimes you need the index, not the value. That’s what findLastIndex() provides. It returns the index of the last matching element, or -1 if nothing matches.

const numbers = [1, 5, 3, 8, 2, 9, 4]
const lastLargeIndex = numbers.findLastIndex(n => n > 7)
// 5 (the index of 9)

Use findLastIndex() when you need to splice, slice from that position, or reference neighboring elements.

Browser Compatibility and Fallbacks

Both findLast() and findLastIndex() are part of ES2023 and have wide support in modern browsers and recent Node.js versions. However, older environments may not include them.

If TypeScript complains about these methods, your tsconfig.json likely needs "lib": ["ES2023"] or newer in the compiler options.

For environments without native support, here’s a clean fallback that doesn’t mutate the original array:

function findLast(arr, predicate) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (predicate(arr[i], i, arr)) {
      return arr[i]
    }
  }
  return undefined
}

This reverse loop is efficient—it stops at the first match and avoids creating intermediate arrays.

Common Pitfalls to Avoid

Don’t reverse the array to use find():

// ❌ Mutates the original array!
const last = arr.reverse().find(x => x > 5)

// ✅ Use findLast instead
const last = arr.findLast(x => x > 5)

Calling reverse() modifies your array in place. This creates subtle bugs that are painful to debug.

Don’t confuse the return values:

  • findLast() returns the element or undefined
  • findLastIndex() returns the index or -1

Checking for truthiness works for findLast(), but with findLastIndex() you must explicitly check for -1:

const index = arr.findLastIndex(x => x > 100)
if (index !== -1) {
  // Found it
}

Watch out for falsy matches:

If your array contains 0, false, or empty strings, ensure your predicate handles them correctly:

const values = [1, 2, 0, false, 'last']
values.findLast(x => x)        // 'last' (skips falsy values)
values.findLast(() => true)    // 'last' (gets actual last element)

When to Choose Each Approach

NeedMethod
Last element matching a conditionfindLast()
Index of last matching elementfindLastIndex()
Simple last element (no condition)arr.at(-1) or arr[arr.length - 1]
Exact value lookuplastIndexOf()

Conclusion

To get the last matching array value in JavaScript, reach for findLast() first. It’s readable, doesn’t mutate your data, and stops as soon as it finds a match. When you need the position instead of the value, use findLastIndex(). For older environments, a simple reverse loop provides a reliable fallback without the mutation risks of reverse(). Keep your predicates explicit, and remember the different return values—undefined versus -1—to avoid silent failures.

FAQs

Yes, findLast() works on sparse arrays. It iterates backward through the array and skips empty slots, only invoking the predicate for elements that actually exist. This behavior mirrors how find() handles sparse arrays when iterating forward.

findLast() is more efficient because it stops iterating as soon as it finds a match. Using filter().pop() processes the entire array first, creating a new array in memory, then retrieves the last element. For large arrays, findLast() offers significant performance gains.

Yes, findLast() supports TypeScript generics and type narrowing. When you use a type guard as your predicate, TypeScript correctly infers the narrowed type for the returned element. Ensure your tsconfig.json includes ES2023 in the lib array for proper type definitions.

Yes, you can add a polyfill to Array.prototype if the method doesn't exist. Check for the method's existence first, then assign a function that loops backward through the array. Core-js and other polyfill libraries also provide ready-made implementations for broader compatibility.

Complete picture for complete understanding

Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Check our GitHub repo and join the thousands of developers in our community.

OpenReplay