Get Index of Object in Array by Property in JavaScript

When you have an array of objects, finding if an object exists in it is trickier than if the array was of primitives, like strings or numbers.
This is because objects can take many different forms and have different data values in them.
In this post, we'll learn how you find the index of an object in an array by property in JavaScript.
Finding the Index of an Object in an Array by Property
First let's start off with an example object:
const object = {
name: "John",
age: 30
};
This is an object with two properties, name
and age
. Now imagine you have an array of objects like these:
const array = [
{
name: "John",
age: 30
},
{
name: "Sally",
age: 40
}
];
To find the object by property, we can use the built-in findindex
method.
This array method is called on the array itself, and you must provide it with a callback function.
This callback function is what determines if the current element in the array is what you're looking for.
If we want to find a person named John
who has the age of 30
, we can provide a function that checks both values:
const object = {
name: "John",
age: 30
};
const array = [
{
name: "John",
age: 30
},
{
name: "Sally",
age: 40
}
];
const index = array.findIndex((person) => {
return person.name === object.name && person.age === object.age;
});
console.log(index);
0
As expected, we get the value 0
back, which is the index of the first element in the array that matches the criteria.
This function would return -1
if the object wasn't found, which is important to remember.
Using the return value, we can turn the return value into a boolean:
const exists = array.findIndex((person) => person.name === object.name && person.age === object.age) > -1;
console.log(exists);
Depending on what you pass in as the callback function, you have full control over when the element fits what you're looking for.
Conclusion
In this post, we learned how to find the index of an object in an array by property in JavaScript.
Make use of the powerful findindex
method and pass it a callback function describing your criteria to find the object.
Hopefully, this has been helpful. Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!