JavaScript: Checking if an array contains a given object

Updated: February 19, 2023 By: Khue Post a comment

In JavaScript, arrays are commonly used to store a collection of values. There might be scenarios where you want to check whether an array contains a given object (this can be a shallow or a deeply nested object).

An object isn’t like a number or a string. You can’t use the Array.includes() method to check if an object is an element of an array. Instead, you need to iterate through the array and compare its elements to the object. Using the === operator to compare 2 objects doesn’t work in this case. A good solution here is to use JSON.stringify().

Example:

// define the check function
const check = (arr, obj) => {
    for (let i = 0; i < arr.length; i++) {
      if (JSON.stringify(arr[i]) === JSON.stringify(obj)) {
        return true;
      }
    }
    return false;
  }

// an array of deeply nested objects about employees in a company
const employees = [
  {
    name: 'John',
    age: 30,
    contact: {
      email: '[email protected]',
      phone: 123,
    },
  },
  {
    name: 'Jane',
    age: 25,
    contact: {
      email: '[email protected]',
      phone: 456,
    },
  },
];

// some person object
// we need to check if this person is in the employees array
const somePerson = {
  name: 'John',
  age: 30,
  contact: {
    email: '[email protected]',
    phone: 123,
  },
};

// Do the check
console.log(check(employees, somePerson));

Output:

true

Code Explained

The check() function loops through each element in the input array and uses JSON.stringify() to compare the string representations of the elements with the string representation of the object we’re checking for. If there’s a match, it returns true. If it reaches the end of the loop without finding a match, it returns false.

You can find more advanced techniques to compare complex objects in this article: 3 Ways to Compare 2 Objects in Javascript.