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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const users = [{id:1, name:"john"}, {id:2, name: "smith"}, {id:3, name:"david"}]; const index = users.findIndex((user)=>{ return user.id===3 }); if(index===-1){ console.log("user not found"); } else{ console.log("the user is in the array") } // output : the user 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.