To get index of an object by property in JavaScript array –
- Use the findIndex() method and pass a function that does an equality check on the desired property.
- Use can also use the map() and indexOf() methods to get the index of an object by property.
Get Index Of An Object By Property In JavaScript Array
Let’s look at both these methods in detail.
The findIndex() method returns the index of the first element in an array that passes a test specified in a function.
So we can use it to get the index of an object like this:
const arr =
//array of objects
[ {name: ‘John’, age: 20},
{name: ‘Jane’, age: 25},
{name: ‘Mike’, age: 30}];
arr.findIndex(obj => obj.name === ‘Jane’) //1
In the above code, we have an array of objects.
Each object has a name and age property.
We use the findIndex() method to get the index of the object where the name is ‘Jane’.
The findIndex() method takes a callback function as an argument.
This callback function takes in an element (in our case, an object) and returns a boolean.
If the boolean is true, then findIndex() will return the index of that element.
Otherwise, it will keep looking until it finds an element that passes the test or until it reaches the end of the array.
If no element passes the test, findIndex() will return -1.
Note that the findIndex() method is not supported by internet explorer.
Using The map() And indexOf() Methods
Another way to get the index of an object by property is to use the map() method.
The map() method creates a new array with the results of calling a function for every element in an array.
So we can use it like this:
const arr =
//array of objects
[{name: ‘John’, age: 20},
{name: ‘Jane’, age: 25},
{name: ‘Mike’, age: 30}];
const names = arr.map(obj => obj.name) // [‘John’,’Jane’,’Mike’]
console.log(names.indexOf(‘Jane’)); //1
In the above code, we have an array of objects.
We use the map() method to create a new array with just the names of each object.
Then we use the indexOf() method to get the index of ‘Jane’.
The indexOf() method returns the first index at which a given element can be found in an array or -1 if it is not present.
So those are two ways to get the index of an object by property in JavaScript.
I hope this was helpful.