Get Index of Object in Array by Property in JavaScript

Updated onbyAlan Morel
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:

JAVASCRIPT
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:

JAVASCRIPT
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:

JAVASCRIPT
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);
BASH
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:

JAVASCRIPT
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.