Find the First Array Element matching a Condition in JS

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

Find the First Array Element matching a Condition #

To find the first array element that matches a condition:

  1. Use the Array.find() method to iterate over the array.
  2. Check if each value matches the condition.
  3. The find method returns the first array element that satisfies the condition.
index.js
const arr = [1, 2, 3, 4, 5]; const result = arr.find(element => { return element > 2; }); console.log(result); // 👉️ 3

The function we passed to the Array.find method gets called with each element in the array until it returns a truthy value or iterates over the entire array.

Truthy values are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the function we passed to the find method returns a truthy value at least once, the find method short-circuits and returns the corresponding array element.

In the example, we check if the current array element is greater than 2. The first element in the array that is greater than 2 is 3.

As soon as the condition is met, the find method short-circuits and returns the value.

This is efficient because we don't have to keep iterating over the array unnecessarily after we've found the item.

If the function never returns a truthy value, the find method will have to iterate over the entire array and will return undefined.

index.js
const arr = [1, 2, 3, 4, 5]; const result = arr.find(element => { return element > 20000000; }); console.log(result); // 👉️ undefined

The implemented condition is never satisfied, so the find() method iterated over the entire array and ended up returning undefined.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.