JavaScript ES6 – Array indexOf method
JavaScript indexOf()
method is used to return index of first matching element from an array, will return -1
if no match was found.
Think of JavaScript array indexOf()
method as: “I want to find the index number of an element within the array.”
JavaScript 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.
array indexOf()
parameters
JavaScript array 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’s see an example on how to use JavaScript array indexOf()
method:
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 12
in 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 0
and 1
, as result the output is 3
.
array indexOf()
usage and tips
- Use
indexOf()
to find index of first matching element - If match found
index
is returned - No match found
-1
is returned - Pass second parameter
fromIndex
to start searching array from specific index