How to check if a value exists in an Array of Objects in JavaScript

#javascript #array

Last updated on Sep 17, 2020 by Suraj Sharma



In this tutorial, you will learn how you can check if an object value exists in an array of objects.


Let’s consider we have an array of objects, each object has a unique identifier username, which can’t be repeated between the objects in the array.


const users = [{
  username: 'suraj123',
  name: 'Suraj',
},
{
  username: 'mike1',
  name: 'Mike',
},
{
  username: 'lisa78',
  name: 'Lisa',
}];

// user object to check in the users array

const user = {
  username: 'mary56',
  name: 'Mary'
};


Two array methods to check for a value in an array of objects



1. Array.some()


The some() method takes a callback function, which gets executed once for every element in the array until it does not return a true value.

The some() method returns true if the user is present in the array else it returns false.

You can use the some() method to check if an object is in the array.


users.some(function (u) {
  if (u.username === user.username)
    return true;
  return false;
})

// false


// using an arrow function

users.some(u=>u.username === user.username)

// false


2. Array.find()


The find() method is available since ES6 and is not supported in Internet Explorer.

The find() method takes a callback function, which gets executed once for every element until it does not return a truthy value.


users.find(u=>u.username === user.username))
// undefined

// a new user object with a username
// that already present in the users array

const user1 = {
  username: 'lisa78',
  name: 'Lovely'
}

users.find(u=>u.username === user1.username)

// { username:"lisa78", name:"Lisa" }


The find() method returns a user that matches the condition.

However, it returns an undefined value if the user is not present in the array.



Related Articles



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.