How to Check if an Object is in Array in JavaScript

Working with an array of objects, checking if an object is in the array is a very common problem. A very simple solution to this problem is to use the findIndex method available in JavaScript.

Checking if an Object is in an Array with findIndex

You can use the findIndex method to check if the object is in an array or not. The findIndex method will return -1 if the element is not in the array and will return the index of the object if it is in the array. The following example uses findIndex method to check if the object is in the array.

findIndex Parameter and Return type

The findIndex array method expects a callback function where you specify a condition. It returns a number. If the object is not in the array, it will return -1 and returns an index if the object satisfies the condition.

You can read more about findIndex on mozilla documenation. If you want to see the difference between indexOf and findIndex please check our blog.

Conclusion

The easiest way to check if an object is in an array is to use findIndex the array method. This method returns -1 if the object is not in the array and returns the index if found.

Latest articles

Related articles