Sometimes, we want to find the index of an object whose attributes match a search in an array of objects with JavaScript.
In this article, we’ll look at how to find the index of an object whose attributes match a search in an array of objects with JavaScript.
How to find the index of an object whose attributes match a search in an array of objects with JavaScript?
To find the index of an object whose attributes match a search in an array of objects with JavaScript, we can use the findIndex
method.
For instance, we write
const index = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }].findIndex(
(obj) => obj.id === 3
);
to call findIndex
to find the item that has id
set to 3 in the
[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
array and return the index of the match.
Conclusion
To find the index of an object whose attributes match a search in an array of objects with JavaScript, we can use the findIndex
method.