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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
const users = [ { id:1, username: "johnsmith", firstName: "john", lastName: "smith" }, { id:2, username: "davidhone", firstName: "david", lastName: "hone" }, { id:3, username: "alexhale", firstName: "alex", lastName: "hale" } ]; const alex = users.findIndex((user)=>{ return user.username === "alexhale" }); console.log(alex) // output : 2 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
const users = [ { id:1, username: "johnsmith", firstName: "john", lastName: "smith" }, { id:2, username: "davidhone", firstName: "david", lastName: "hone" }, { id:3, username: "alexhale", firstName: "alex", lastName: "hale" } ]; const index = users.findIndex((user)=>{ return user.username === "alexhale" }); if(index===-1){ console.log("The user not found!") } else{ console.log("The index of user is ", index) } |
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.