Often times in our code, we want to get an object from a JavaScript array that matches the given condition.
In this article, we’ll look at how to find the index of the object that matches the given condition in a JavaScript array.
Array.prototype.findIndex
We can use the JavaScript array’s findIndex
method to let us get the index of the object in an array that matches the given condition.
To use it, we write:
const arr = [{
name: 'james'
},
{
name: 'mary'
},
{
name: 'jane'
}
];
const index = arr.findIndex(x => x.name === "jane");
console.log(index);
We pass in the findIndex
method with a callback that finds the item where the name
property’s value is 'jane'
.
Therefore, index
should be 2.
Lodash findindex Method
If we’re using Lodash in our JavaScript project, we can also use its findIndex
method to find the object that matches the given condition in an array.
For instance, we can write:
const arr = [{
name: 'james'
},
{
name: 'mary'
},
{
name: 'jane'
}
];
const index = _.findIndex(arr, x => x.name === "jane");
console.log(index);
to pass in the array to the 1st argument and the callback into the 2nd argument.
And we get the same result for index
.
We can also pass in an object with the properties to search for.
To do this, we write:
const arr = [{
name: 'james'
},
{
name: 'mary'
},
{
name: 'jane'
}
];
const index = _.findIndex(arr, {
name: 'jane'
});
console.log(index);
And we get the same result.
Array.prototype.map and Array.prototype.indexOf
Another way to find an object in an array that meets the given condition is to map the property values we’re looking for with the map
method.
Then we can use indexOf
to find the index of the given value assuming the property holds a primitive value.
For instance, we can write:
const arr = [{
name: 'james'
},
{
name: 'mary'
},
{
name: 'jane'
}
];
const index = arr.map(a => a.name).indexOf('jane')
console.log(index);
We call map
to return an artay with all the name
property values from each object.
Then we can call indexOf
with what we’re looking for.
And so index
should be the same as the other examples.
Conclusion
We can get the index of an object in a JavaScript array that meets the given property value with various array methods.