JavaScript offers many methods whose functionality can be used to check for objects inside arrays. We’ll look at most of them in great detail:
arr.some() Method
The some() method takes a function as an argument which checks if any element of the array contains a specific property value. If that property value is found then the method returns true:
let found = employees.some(obj => {
if (obj.age == 40) {
returntrue;
}
returnfalse;
});
console.log(found);
Else it returns false:
let found = employees.some(obj => {
if (obj.age == 55) {
returntrue;
}
returnfalse;
});
console.log(found);
arr.includes() Method
The includes method takes an object as an argument and returns true if it is present inside an array:
let emp2 = {firstName:"Adam", lastName:"Smith", age:40};
let employees = [emp1, emp2];
let found = employees.includes(emp1);
console.log(found);
It is important to note that the argument object and the object inside the array should be the same. Different objects with same values will return false:
let found = employees.includes({firstName:"Adam", lastName:"Smith", age:40});
console.log(found);
arr.find() Method
The find() method is similar to the some() as it checks for specific property values but if found, it returns the object instead of true value:
let found = employees.find(obj => {
if (obj.age == 40) {
returntrue;
}
returnfalse;
});
console.log(found);
If the object is not present then the find() method returns undefined:
let found = employees.find(obj => {
if (obj.age == 28) {
returntrue;
}
returnfalse;
});
console.log(found);
arr.filter() Method
The filter() method can be applied on an array to get a list of all the objects that pass certain conditions:
let found = employees.filter(obj => {
if (obj.age == 40) {
returntrue;
}
returnfalse;
});
console.log(found);
arr.findIndex() Method
The findIndex() method will check for specific property value and return the index of the found object:
let found = employees.findIndex(obj => {
if (obj.age == 40) {
returntrue;
}
returnfalse;
});
console.log(found);
If the object is not found then it returns -1:
let found = employees.findIndex(obj => {
if (obj.age == 99) {
returntrue;
}
returnfalse;
});
console.log(found);
Conclusion
In this write-up we went over several ways of checking if an array contains an object in JavaScript. All of these methods have a few differences in how they work. These differences were mentioned and comprehensively discussed in the post above.