JavaScript Arrays: Find
Welcome to the Find lesson!
JavaScript arrays' `.find` method returns the first array element where the given function is true.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Sometimes we need to find an element that matches a condition. We already saw
.findIndex, which returns the index of a matching element. Now let's write our own.findfunction that returns the matching element itself.Our function first gets the index of the matching element with
.findIndex. If the index is-1, the element wasn't found, so we returnundefined. Otherwise, we return the element at that index.>
function find(array, callback) {const index = array.findIndex(callback);if (index === -1) {return undefined;} else {return array[index];}}find([5, 6, 7], n => n / 2 === 3);Result:
6
Fortunately, JavaScript arrays have a built-in
.findmethod, so we don't have to write it ourselves.>
[5, 6, 7].find(n => n / 2 === 3);Result:
6
We can use this to find objects with certain properties.
>
const users = [{name: 'Amir', admin: false},{name: 'Betty', admin: true},];users.find(user => user.admin).name;Result:
'Betty'
If there are multiple matches,
.findwill return the first matching element. This is the same behavior we saw with.indexOfand.findIndex.In the next example, we use
.findto match every even number in the array. (The modulo operator%returns the remainder of a division.n % 2 === 0is true whennis even.)>
const numbers = [1, 2, 3, 4, 5, 6];numbers.find(n => n % 2 === 0);Result:
Sometimes we want to find multiple elements that match a condition. The
findmethod can't do that, but thefiltermethod can. We'll seefilterin another lesson.