This post will discuss how to determine whether an object is present in a JavaScript array.

JavaScript native methods indexOf() and includes() compare by using the strict equality operator (===). This won’t work for object comparison, as shown below:

Download  Run Code

 
This post provides an overview of some of the available alternatives to accomplish this.

1. Using _.some() method

If you’re already using the Lodash library, consider using the _.some method. It returns true if a JavaScript array contains an object.

Download Code

 
Alternatively, you can use the _.some method of the Underscore library.

Download Code

2. Using JSON.stringify() function

Here, the idea is to convert the given object into a string using the JSON.stringify() method. Then we compare the string representation of the object against each entry in the array using the strict equality operator (===). This can be done using any of the methods discussed here.

Download  Run Code

That’s all about checking if an object is present in a JavaScript array.