indexOf() method is used to return index of first matching element from an array, will
return -1 if no match was found.
indexOf() method as: “I want to find the index number of an element within the array.”
indexOf() method is similar to
findIndex() method but there is slightly usage difference between the 2 methods. You want to know the difference visit What are the difference between indexOf and findIndex method article.
indexOf() method consists of following parameters:
- searchElement – the element value you want to find the index in array
- fromIndex – array index to start the search, optional if dont need to skip any elements from search
let arr = [19, 12, 32, 12, 25]; const index = arr.indexOf(12); console.log(index); // OUTPUT: // 1
In above example we are searching for index of
arr array, and
1 is returned as result which is expected.
But notice we have another element with
12 value in the array. Keep in mind
indexOf() method returns the index for the first matching element.
Let’s see another example:
let arr = [19, 12, 32, 12, 25]; const index = arr.indexOf(12, 2); console.log(index); // OUTPUT // 3
This time we are passing second parameter
indexFrom => 2, we want to start the search from array index
2 and skip array index
1, as result the output is
indexOf() usage and tips
indexOf()to find index of first matching element
- If match found
- No match found
- Pass second parameter
fromIndexto start searching array from specific index