Javascript check if array contains an Object

Javascript Check if an Array contains an Object Example; In this tutorial you will learn how to check if a JavaScript array contains an object.

Example 1: Check if an Array Contains an Object with Array.find

To check if an array includes an object in JavaScript we can use Array.find. The Array.find method will return the object if the conditional check is satisfied at least once

const users = [
  {id: 1, name: 'Test 1'},
  {id: 2, name: 'Test 2'},
];

const user = users.find(element=> {
  if (element.id === 1) {
    return true;
  }

  return false;
});

console.log(user ); // { id: 1, name: 'Test 1' }
if (user !== undefined) {
  // object is contained in array
}

Example 2: Check if an Array Contains an Object with Array.filter

To check if an array includes an object in JavaScript we can use Array.filter. The Array.filter method method will return an array containing the objects that satisfy the conditional check (if any).

const users = [
  {id: 1, name: 'Test 1'},
  {id: 2, name: 'Test 2'},
];

const userArray = users.filter(element=> {
  if (element.id === 1) {
    return true;
  }

  return false;
});

console.log(userArray ); // 👉️ [ { id: 1, name: 'Test 1' } ]

if (userArray.length > 0) {
  // object is contained in the array
}

Example 3: Check if an Array contains an Object with Array.some

To check if an array contains an object in JavaScript we can use Array.some. The Array.some method will return true is the conditional check is satisfied at least once.

const users = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Adam'},
];

const isFound = users.some(user=> {
  if (user.id === 1) {
    return true;
  }

  return false;
});

console.log(isFound); // true

if (isFound) {
  // object is contained in array
}

I hope these examples help you.