How to Check if an Array Contains an Object in JavaScript
Checking if an array contains a specific object is a common task, but it's more complex than checking for a primitive value like a string or number. Because objects are compared by reference, not by value, you can't simply use array.includes({ id: 1 }). Instead, you must iterate through the array and check for an object with a specific property value.
This guide will cover the best modern JavaScript methods for this task, explaining the distinct use case for each one, from getting a simple true/false result to finding all matching objects.
Core Problem: Objects are Compared by Reference
It is critical to understand why methods like includes() fail for this task. includes() uses strict equality (===), which for objects, checks if they are the exact same instance in memory.
Example of the problem:
// Problem: How to find an object with id: 1?
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
// This does NOT work because the object we are searching for is a new,
// different object in memory, even though its contents are identical.
const hasJohn = people.includes({ id: 1, name: 'John' });
console.log(hasJohn); // Output: false
To solve this, we must check for an object by one of its property values.
To Get a true/false Result: Array.prototype.some()
Use Case: When you only need to know if an object with a certain property exists, and you don't need the object itself.
The some() method is the most efficient tool for this. It iterates over the array and returns true as soon as the callback function returns a truthy value, then immediately stops.
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
const hasObjectWithId = people.some(person => person.id === 1);
console.log(hasObjectWithId); // Output: true
This is the best method for a simple existence check because it short-circuits, preventing unnecessary iterations.
To Get the Matching Object: Array.prototype.find()
Use Case: When you need to retrieve the first full object that matches your condition.
The find() method iterates over the array and returns the first element that satisfies the testing function. If no match is found, it returns undefined.
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
const foundPerson = people.find(person => person.id === 1);
console.log(foundPerson); // Output: { id: 1, name: 'John' }
if (foundPerson) {
console.log(`Found person's name: ${foundPerson.name}`);
}
Like some(), find() also short-circuits, making it very efficient.
To Get the Index of the Object: Array.prototype.findIndex()
Use Case: When you need the position (index) of the first matching object in the array, for example, to later update or remove it.
The findIndex() method returns the index of the first element that satisfies the condition. If no match is found, it returns -1.
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
const indexOfPerson = people.findIndex(person => person.id === 1);
console.log(indexOfPerson); // Output: 0
if (indexOfPerson !== -1) {
console.log('Object found at index:', indexOfPerson);
}
To Get All Matching Objects: Array.prototype.filter()
Use Case: When you need to find all objects in an array that match a condition, not just the first one.
The filter() method iterates over the entire array and returns a new array containing all elements that pass the test. If no matches are found, it returns an empty array.
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
{ id: 1, name: 'Johnny' } // Another object with id: 1
];
const foundPeople = people.filter(person => person.id === 1);
console.log(foundPeople); // Output: [ { id: 1, name: 'John' }, { id: 1, name: 'Johnny' } ]
if (foundPeople.length > 0) {
console.log(`Found ${foundPeople.length} matching objects.`);
}
filter() does not short-circuit; it always iterates through the entire source array.
The Manual Approach: Using a for...of Loop
Use Case: When you need full control over the iteration or have complex logic inside the loop that requires a break or other statements.
While functional methods are usually cleaner, a for...of loop is the foundational way to iterate and is perfectly valid.
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
let isFound = false;
let foundPerson = null;
for (const person of people) {
if (person.id === 1) {
isFound = true;
foundPerson = person;
break; // Exit the loop early for efficiency
}
}
console.log(isFound); // Output: true
console.log(foundPerson); // Output: { id: 1, name: 'John' }
How to Check if an Object is NOT in an Array
To check for the absence of an object, the cleanest method is to negate the result of some().
Example:
const people = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Adam' },
];
const isNotInArray = !people.some(person => person.id === 3);
console.log(isNotInArray); // Output: true
if (isNotInArray) {
console.log('Confirmed: No person with id: 3 is in the array.');
}
Conclusion
JavaScript's modern array methods provide a specific tool for every need when searching for objects in an array.
- To check for existence (
true/false): Usesome()for its efficiency. - To get the first matching object: Use
find(). - To get the index of the first match: Use
findIndex(). - To get all matching objects: Use
filter(). - To check for absence: Use the negated
some()pattern:!array.some(...).
By choosing the right method for your specific goal, you can write code that is not only correct but also clean, readable, and efficient.