Sling Academy
Home/JavaScript/JavaScript: Checking if an array contains a given object

JavaScript: Checking if an array contains a given object

Last updated: February 19, 2023

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.

Next Article: 5 Ways to Convert an Array to an Object in JavaScript

Previous Article: JavaScript: How to iterate through 2 arrays in parallel

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration