If you want to find or get an element’s first position or index in an array. You can use the findindex() function; In this tutorial, we will show you how to find or get the first occurrence element position or index in a JavaScript array using the js array method.
How to Get or Find First Index of Element in Array JavaScript
The FindIndex method helps you to get the first index or position of occurrence element in the array that satisfies the given specific test condition.
The basic Syntax of the findIndex()
method
The following syntax demonstration of the findIndex()
method:
findIndex(callback(element[, index[, array]])[, thisArg])
Parameters
The findIndex()
takes two parameters:
- The first one is the
callback
function and it’s optional. - The second one is used as
this
inside thecallback
.
1) callback
The callback
is a function to execute on each element of the array. It accepts 3 parameters:
element
is the current element of an array.index
the index of the current element of an array.array
the array that thefindIndex()
was called upon.
2) thisArg
The thisArg
parameter is an optional object to be used this
when executing the callback
. If you omit the thisArg
argument, the findIndex()
function uses undefined
.
Return value
For each element of an array, The findIndex()
executes the callback
function until the callback
returns a truthy value. In this case, the findIndex()
immediately returns the value of that element. Otherwise, it returns undefined
.
Note that, JS findIndex()
method is truly different from the find()
method, The find()
method is used to search the first element in an array.
Examples of Get/Find Index of First Element in Array JavaScript
First, you have an array with some items. Let’s say it’s an array of numbers.
const numbers = [1, 2, 3, 4, 5];
Now you want to find the position of first odd number from array. You can use findIndex function like following:
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.findIndex(e => e % 2 == 1));
Output:
0
If you want to find first even number index or position in an array, you can do it by using the following:
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.findIndex(e => e % 2 == 0));
Output:
1
Suppose that you have a list of computers objects with name
and price
properties as follows:
let computers = [{ name: 'Dell', price: 60000 }, { name: 'HP', price: 50000 }, { name: 'Apple', price: 80000 }];
The following javascript code uses the findIndex()
method to find the first computer position in an array, whose price is greater than $ 60000.
let computers = [{ name: 'Dell', price: 60000 }, { name: 'HP', price: 50000 }, { name: 'Apple', price: 80000 }]; console.log(computers.findIndex(c => c.price > 60000));
Output:
2
Conclusion
That’s it; you have learned how to use the JavaScript Array’s findIndex()
method to get or find the first occurrence element position or index in an array.