The JavaScript array.find() method
The find() method returns the first element in an array that passes your test, or undefined if none do. users.find(u => u.id === 42) grabs the matching user object. Use it when you want one item; use filter() when you want every match.
Overview
find() searches an array and returns the first element for which your callback returns a truthy value. It's built for the very common job of looking something up — the user with a given ID, the first product under a price, the first error in a list. As soon as it finds a match it stops and returns that element, so it doesn't waste time scanning the rest.
If nothing matches, you get undefined back, so check for that before using the result. The callback takes the usual element, index and array arguments. If you want the position of the match rather than the element itself, its sibling findIndex() returns the index (or -1).
The difference from filter() is the one people most often get wrong: filter() always returns an array (possibly with many items), while find() returns a single element. And unlike indexOf(), which only checks for an exact value, find() lets you match on any condition — perfect for arrays of objects.
Syntax
const element = array.find(callbackFn)
const element = array.find(callbackFn, thisArg)
array.find((element, index, array) => {
return /* true for the element you want */;
})
Parameters
The array.find() method accepts the following parameters.
| Parameter | Description |
|---|---|
callbackFn |
Test run for each element until one returns truthy. Receives (element, index, array). |
thisArg |
Optional. A value to use as this inside the callback. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const users = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
{ id: 3, name: 'Linus' }
];
const user = users.find(u => u.id === 2);
document.getElementById('out').textContent =
user ? user.name : 'not found'; // Grace
</script>
Best practices
- Always handle the
undefinedcase —find()returns it when nothing matches. - Use
find()for a single result and filter() for all results; don'tfilter()[0]. - Use
findIndex()instead when you need the position of the match rather than the element. - For a plain "is this value present?" check, includes() is simpler than
find().
Frequently asked questions
What does find() return if nothing matches?
undefined. Always check the result before using it, e.g. const u = users.find(...); if (u) { ... }.What is the difference between find() and filter()?
find() returns the first matching element; filter() returns an array of all matching elements. Use find() for one, filter() for many.How do I find an object in an array by a property?
items.find(item => item.id === 42).What is the difference between find() and indexOf()?
find() runs a test function and returns the element, which is what you need for arrays of objects.