Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

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]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have an array and want one item that meets a condition. What does find() return?

Geez

find() calls your condition on array items in ascending index order and returns the first item for which the condition produces a truthy result. It stops when it finds that item. If nothing matches, the return value is undefined. [S1]

For example, suppose scores contains numbers and you need the first score above 10:

const scores = [5, 12, 18];
const firstHighScore = scores.find(score => score > 10);

console.log(firstHighScore); // 12

The result is the matching array value, not a new array of matches. In this example, 18 also meets the condition, but find() returns 12 because it comes first.

Follow-up question

How do I look up an object in an array, and what happens if it is missing?

Geez

Put the lookup condition in the callback. For instance, assuming this example array has objects with an id property:

const people = [
  { id: 1, name: "Mina" },
  { id: 2, name: "Omar" }
];

const person = people.find(item => item.id === 2);
const missingPerson = people.find(item => item.id === 3);

console.log(person);        // { id: 2, name: "Omar" }
console.log(missingPerson); // undefined

The second lookup has no match, so it returns undefined rather than an object or an empty array. [S1] Before reading a property from a result that might be missing, check it:

if (person !== undefined) {
  console.log(person.name);
}

This keeps the no-match case explicit. Adapt the property names and values to your own data.

Follow-up question

How can I make the no-match case safe without assuming an item exists?

Geez

Store the result, then branch on whether it is undefined before using it. Here is a copyable pattern, using a placeholder condition you can replace:

const item = items.find(entry => entry.key === wantedKey);

if (item === undefined) {
  console.log("No matching item");
} else {
  console.log(item);
}

The items, key, and wantedKey names are placeholders; use the array and condition from your program. For arrays of objects like this example, the check makes the no-match case explicit. If your array can contain undefined as a matching value, that result alone cannot distinguish a match from no match. find() uses the callback result as a condition and returns the array element when that result is truthy. [S1]

Follow-up question

What if I need every match, or want to make sure I am asking for the right thing?

Geez

Use find() when the task is “give me the first matching item.” If the task is “give me all matching items,” use filter() instead; that is the method MDN identifies for obtaining all matches. [S1] For example, with [5, 12, 18], scores.find(score => score > 10) gives 12, while scores.filter(score => score > 10) gives [12, 18].

Before writing the callback, state the condition in plain language: “the first item whose ___ is ___.” Then check that the property and comparison in your code express that condition. The example illustrates the method’s behavior; it does not establish how any particular application’s data is structured.

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 undefined before 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.

  1. [S1] Array.prototype.find() — JavaScript | MDN
    developer.mozilla.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work