July 7, 2020
How to Check if an Array Includes Reference of an Object in Javascript
- We have selected two elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have two global variables
obj
andusers
.obj
holds an object as its value and users holds an array of strings plusobj
variable as part of the array. - We have attached the
click
event listener to thebutton
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 theuser.includes()
method to check ifobj
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'; });
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
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.button
element is“Check”
and for theh1
element is “Result”.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript