In this tutorial, you will learn JavaScript findIndex()
method and how to search the first occurrence element index or position in an array using this javascript array method.
findIndex()
methodYou can use the new method findIndex()
to find first occurrence position of an array. Because in es6 enhance the capability to finding the first position of an element in the javascript array
findIndex()
methodThe following syntax demonstration of the findIndex()
method:
findIndex(callback(element[, index[, array]])[, thisArg])
The findIndex()
takes two parameters:
callback
function and it’s optional.this
inside the callback
.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 the findIndex()
was called upon.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
.
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.
findIndex()
Suppose you have a numeric array and want to search the first odd number position in it, you can use these findIndex()
method for these.
See the following example:
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 find 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
In this tutorial, you have learned how to use the JavaScript Array’s findIndex()
method and using this method how to find the first occurrence Index or position in an array.
☞ Learn JavaScript - Become a Zero to Hero
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ 8 Useful JavaScript Array Methods
☞ JavaScript Fill Method Complete JS Array Methods Series
☞ JavaScript shift and unshift Method Complete JS Array Methods Series