How to Get the Index of an Array that Contains Objects in JavaScript
Read this JavaScript tutorial and learn several useful, fast and simple methods that are used for getting the index of an array that contains objects.
There are several methods in JavaScript that can help you access the index of an object within an array. While older or less efficient approaches exist, the modern standard is findIndex(). Let’s look at each method to understand their differences.
map()
The <kbd class="highlighted">map()</kbd> method creates a new array by calling a function for every element. While it works, it is inefficient for simply finding an index because it builds an intermediate array and then searches it. A more direct approach is preferred:
for loop
Another approach is a for loop defined inside a custom prototype method. Note that modifying built-in prototypes like Array.prototype is generally discouraged in modern JavaScript due to potential naming conflicts and performance overhead. This method is mainly shown for historical context:
findIndex()
The recommended modern solution is the native findIndex() method:
The <kbd class="highlighted">Array.prototype.findIndex()</kbd> method returns the index of the first element that satisfies the provided testing function; otherwise, it returns -1. It executes the callback once per index until a match is found, making it both efficient and readable.