How to Find Index of an Object in Array in JavaScript

Working with APIs of real data gives you an array of objects. You often need to find the index of an object in an array. After reading this article, you will know how you can find the index of any data in an array.

Using findIndex to Get an Index in an Array

You can simply use findIndex method to get the index of an object in an array. The findIndex method takes a callback function as an argument and returns the index based on the condition. The following code snippet uses findIndex to get the index of a user from the given data.

 

The findIndex method returns -1 if the condition is not satisfied in the callback function.  You can check the returned value if you want to do something else with the index.

How to Check if the Object Index is Found

The following code example checks the returned value of findIndex . The if else condition checks whether the returned value is -1 or some other number.

Conclusion

You can use findIndex to get the index of an Object in an array. The findIndex method returns the index of the Object if it is found otherwise returns -1 . This method is very useful in situations where you need the index of an object. You can read more about findIndex on Mozilla documentation.

 

Latest articles

Related articles