How to Check if an Array Includes Reference of an Object in Javascript

In this tutorial, you will learn how to check if an array includes a reference of an object in javascript.  Before I start this tutorial, I would like you to know what we are going to do here.

If you are not new to javascript, then you already know that object is a reference type.  We are simply going to check if an array includes a reference of an object or not.

We are not going to cover shallow or deep comparison here.  Maybe in the future tutorial, I will put up a video or article on how to do so.

In the following example, we have one global object.  We simply want to verify if the reference of this object is present in the array or not.  After verification, we will display a Boolean value on the screen.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
        <div>
            <button>Check</button>
            <h1>Result</h1>
        </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected two elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have two global variables obj and users. obj holds an object as its value and users holds an array of strings plus obj variable as part of the array.
  • We have attached the click event listener to the button element.
  • includes() method helps in determining whether an array has a certain item present in its list of items or not.
  • In the click event handler function, we are using the user.includes() method to check if obj is present in the array or not.
  • We are setting the inner text of the h1 element to the Boolean value returned by the above method.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let obj = {name: 'Jane'};
let users = ['Peter', 'Marks', obj];

btnCheck.addEventListener('click', () => {
    result.innerText = users.includes(obj) ? 'True' : 'False';
});