How can I find the first matching array item with `find()`?
Quick answer
find() checks array items in order and returns the first item whose callback result is truthy. If no item matches, it returns undefined. For example, const first = numbers.find(n => n > 10) gives the first number greater than 10. Check the result before using it if the array may contain no match. Use filter() instead when you need every matching item. [S1]
The question, the details, the next step.
A practical checklist
Write down the condition the item must satisfy.
Call
find()on the array and put that condition in its callback.Use the returned item as a single value, not as an array of matches.
Handle
undefinedbefore accessing properties if no match is possible.Use
filter()when you need all matching items instead of only the first.
A few more useful answers
Does `find()` return the index of the matching item?
No. It returns the first matching array element. This guide does not cover index lookup.
What does `find()` return when there is no match?
It returns undefined, so check for that case before using the result as an item. [S1]
Should I use `find()` or `filter()` for several matches?
Use filter() when you need all matching elements; find() returns only the first match. [S1]
Sources
References used for this guide.
- [S1] Array.prototype.find() — JavaScript | MDN developer.mozilla.org · Checked
