When working with arrays, you often faced a situation where you are confused about using indexOf
and findIndex
. This post will help you understand the findIndex
and indexOf
functions and what should be used in different use cases.
indexOf
Array function in JavaScript
The indexOf
function in JavaScript is simply used for finding the index of an element. It returns the index of an element if the element is in the array and returns -1
if the element is not in the array. In the following code snippet, you can see an example of using indexOf
method on an array of numbers.
1 2 3 4 5 6 7 8 |
const numbers = [2,34,5,64,67,90]; const index = numbers.indexOf(67); console.log(index) // output : 4 |
Using indexOf
to Find the Character index in the String
You can also use the indexOf
method to find the index of a character in a string. It will return -1
if the character is not in the string and the actual index if it is found in the string. Check the following example to see how to get the character index in a string.
1 2 3 4 5 6 7 8 |
const string = "javascript"; const index = string.indexOf("s"); console.log(index) // output : 4 |
This method will return the index of the first element if it is found more than once.
This indexOf
the method doesn’t work with an array of objects. The following code will example prints -1
because the data is an object.
1 2 3 4 5 6 7 8 9 |
// the indexOf doesn't work ⛔️ with array of objects const data = [{id:1, name:"john"}, {id:2, name: "smith"}]; const index = data.indexOf({id:1, name:"john"}); console.log(index) // output : -1 |
As you can see in the above example, indexOf
doesn’t work with an array of objects. It only works with numbers or strings. So, if you have an array of objects, you need to use the other method indexOf
.
Using findIndex
method to Find the Index of an Object
When working with an array of objects you might need to find the index of an object. The method findIndex
is very useful in those situations. The findIndex
method expects a callback function as a parameter and you need to specify a condition. The following example explains how to use findIndex
method to get the index of an Object.
1 2 3 4 5 6 7 8 9 10 |
const users = [{id:1, name:"john"}, {id:2, name: "smith"}, {id:3, name:"david"}]; const index = users.findIndex((user)=>{ return user.id===3 }); console.log(index) // output : 2 |
You can read more about finding the index of an object in an array and also check the indexOf and findIndex methods in detail.
Conclusion
JavaScript array methods indexOf
and findIndex
are used to find the element index in an array. The indexOf
method only works with numbers or string arrays and doesn’t work with an array of objects. The method findIndex
is used to get the index of an object from an array of objects.