In this article, you’ll learn how to get the index of an object in a javascript array. There are various ways to find the index of an object in a javascript array such as: the findIndex()
method, map()
method, and Array.forEach()
method.
Here are some examples to get the index of an object in a Javascript array
In this example, We used the ES6 Array.findIndex()
method to get the first index of an item in an array of objects. The findIndex()
method accepts a callback function as its argument, which iterates through all the elements in the array until the condition is not to pass a test. This method returns -1 if no match is found, otherwise, it returns an element index.
Note: The findIndex()
method is not supported in IE(6-11) browsers but you can use a polyfill of Array.findIndex.
In this example, we used the map()
method to get the index of an object in a javascript array. The map()
method creates a new array and calls a function for each element in an array. This method returns -1 if no match is found, otherwise, it returns an element index.
In this example, we used the Array.forEach()
method to get the index of an object in the javascript array.
I hope this article will help you to understand how to get the index of an object in a javascript array.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments