ES6 - Array find method

ES6 JavaScript

In this ES6 tutorial we are going to learn about the array find method. So, let's get started.

In the previous tutorial we learned about Filter method and how we use it to filter out elements of an array based on some filtering condition.

Similarly, we use the find method to get the first matching element of an array that satisfy the condition we have defined. If no element of the array satisfy the conditions then the find method returns undefined.

Find first even number

Let's say we have an array of 5 integer values and we want to find the first even number in that array. In order to achieve this we can take help of the find method.

const arr = [1, 3, 15, 2, 10];
const firstEvenNumber = arr.find(v => v % 2 === 0);
console.log(firstEvenNumber);

Find in array of objects

Let's look at another example. Say, we have an array of objects and each element of the array represent a user. We want to find the first online user object in the array.

const users = [
  { username: 'tom', isOnline: false },
  { username: 'jerry', isOnline: true },
  { username: 'tintin', isOnline: true }
];
const firstOnlineUser = users.find(v => v.isOnline);
console.log(firstOnlineUser);

Alright this brings us to the end of this tutorial. Have fun coding. See you soon in the next tutorial.