Appearance
How to Get the Index of an Array that Contains Objects in JavaScript
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 map() 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:
Output appears here after Run.
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:
Output appears here after Run.
findIndex()
The recommended modern solution is the native findIndex() method:
Output appears here after Run.
The Array.prototype.findIndex() 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.