Javascript ES6 — Array.find() and Array.findIndex() # 9

We’ve here a list of users, so we’ve got an array, and at each index, we’ve got a specific object user that has an id, fullName, email and gender, our goal is, to find a user that matches a specific criteria, as an example we want to search for a user that has a fullName of Rex Michael.

const users = [
  {
    id: 45,
    fullName: "Vasily Maystone",
    email: "[email protected]",
    gender: "Male",
  },
  {
    id: 46,
    fullName: "Artie Mardy",
    email: "[email protected]",
    gender: "Male",
  },
  {
    id: 47,
    fullName: "Rex Michael",
    email: "[email protected]",
    gender: "Male",
  },
  {
    id: 48,
    fullName: "Jenna Belliss",
    email: "[email protected]",
    gender: "Female",
  },
  {
    id: 49,
    fullName: "Harriot Kroll",
    email: "[email protected]",
    gender: "Female",
  },
];

There is an ES6 method designed to achieve that, however, let’s do it manually to understand the concept.

for of

You’ll create a getUser function, that has two parameters, the first one is users, or the array that contain the list of users, and the second parameter is the search criteria fullName.

And you use a for of loop to get into each element of the users array, then, you check the fullName of each user if it’s following the fullName that you’ll specify when you call the function.
So if the condition is true, or if the given fullName exist, return this specific user object, otherwise undefined is returned.

const getUser = (users, fullName) => {
  for (user of users) {
    if (user.fullName == fullName) {
      return user;
    }
  }
};

Now, let’s assign the getUser function to a variable selectedUser, and the first parameter of the function is the list of users, which it’s this array, and the second parameter the fullName you’re searching for.
Okay let’s start with a fullName that doesn’t exist John Doe, and console log the selectedUser.

const selectedUser = getUser(users, "John Doe");
console.log(selectedUser);

You’ve undefined, because the search criteria you’re given doesn’t exist, so no user on the list have a fullName of John Doe, let’s do another test, but now, with an existent fullName "Rex Michael".

const selectedUser = getUser(users, "Rex Michael");

Now this condition is returning true, which means that while the for of loop was iterating over each user of the list, it finds a user with the fullName of Rex Michael which returns the user object.

Okay, I know, that I’m giving you too many details, but I want you to understand how finding elements through arrays works. Let’s now simplify our life by using a function that does all of that without writing this bunch of code.

// const getUser = (users, fullName) => {
//   for (let user of users) {
//     if (user.fullName == fullName) {
//       return user;
//     }
//   }
// };

// const selectedUser = getUser(users, "Rex Michael");
// console.log(selectedUser);

For that, you’ll use the ES6 find method, which executes the callback once for each index of the users array until it finds the user Rex Michael.

The simple definition of the find method, it’s a method that searches for an element that matches a specific condition and returns the first element in the array that satisfies the provided condition. Otherwise undefined is returned

find

Let’s test that by writing some code, but before that, let’s see what the find method returns as values, so you start with the users array, and you use the method find(), then, this function is executing a callback that takes three arguments, the first one is the element, which it’s the equivalent of the current element being processed in the array, you can put any name you want, Okay, let’s put user, the second parameter is the index of the current user element, and the last argument is the users array itself.

Console log the user, which will display each user, console log the index, which will display each index respectively 0, 1, 2, 3, 4 because we’ve 5 elements, and console log users which display the whole array. So, inside this callback you’re doing iterations on each element of the users array, like the previous example.

users.find((user, index, users) => {
  console.log(user);
  console.log(index);
  console.log(users);
});

In general, and for our case, you don’t need these last two parameters index and users,

users.find(user => {
  console.log(user);
});

Now, and to check for a user with the fullName Rex Michael, you’ve two solutions, the first one, is using a condition to check if the user fullName is equal to Rex Michael, if the condition is true, return this specific user object, otherwise it’ll return undefined.

users.find(user => {
  if (user.fullName == "Rex Michael") {
    return true;
  }
});

Let’s assign the returned value to a selectedUser variable, and console log the result

const selectedUser = users.find(user => {
  if (user.fullName == "Rex Michael") {
    return true;
  }
});

console.log(selectedUser);

The second solution, will be simpler, remove all of that, and keep the user argument and the condition, so you’re getting the same result, but in a less code, cool.

const selectedUser = users.find(user => user.fullName == "Rex Michael");

If you remember at the first example, when you create a function getUser to get a specific user by using the for of loop, let’s now achieve the same result using the find method.

So, you create a getUser function that has two arguments, the users list and the given fullName you’re searching for, and instead of a for of loop, you copy this line and you replace the Rex Michael with the fullName argument.

const getUser = (users, fullName) =>
  users.find(user => user.fullName == fullName);

Assign the returned value of the getUser to a selectedUser variable, and for the first argument will be the users arrays, and for the second argument, you define a user you are searching for, let’s do another one Artie Mardy, and you console log the result. Same result with less code and you can dynamically specify any fullName you’re searching for within the users list.

const selectedUser = getUser(users, "Artie Mardy");

findIndex

Let’s now move to another interesting method findIndex, so, if the find method return a value of an array element, the findIndex instead, return the index of this element.

Super simple to use, let’s use the same variable name selectedUser, and assign to it the returned value of the findIndex method for a specific user Jenna Belliss on the users list, if the user exist, you’ll get the index of this specific user,

const selectedUser = users.findIndex(user => user.fullName == "Jenna Belliss");

console log the result to see that, you get 3, which equivalent to its position on the array, so 0, 1, 2, 3.

console.log(selectedUser);

And, if you change this Jenna Belliss to a non-existent user John Doe you’ll get negative one -1, which it’s equivalent to, that the user in question doesn’t exist.

const selectedUser = users.findIndex(user => user.fullName == "John Doe");

Leave a Reply

Your email address will not be published. Required fields are marked *