How to find the first matching element given an array and predicate with JavaScript?

Sometimes, we want to find the first matching element given an array and predicate with JavaScript.

In this article, we’ll look at how to find the first matching element given an array and predicate with JavaScript.

How to find the first matching element given an array and predicate with JavaScript?

The first matching element given an array and predicate with JavaScript, we can use the array find method.

For instance, we write:

const a = [2, 4, 10, 5, 7, 20]
const r = a.find(x => x % 2)
console.log(r)

to find the first element in a that is odd with find.

We call a.find with x => x % 2 to return the first element in a that isn’t evenly divisible by 2.

Therefore, r is 5.

Conclusion

The first matching element given an array and predicate with JavaScript, we can use the array find method.