JavaScript findIndex()
The findIndex()
method is a built-in, higher-order function introduced in ES6 that is used to find the index of the first element in an array that matches the given condition. It returns the index of the found element, or -1 if not found.
Syntax
array.findIndex(callback(element[, index[, array]])[, thisArg])
callback
: a function to execute on each value in the array until the condition is met. It takes three arguments:element
: the current element being checked in the array.index (optional)
: the index of the current element being checked.array (optional)
: the array being checked.
thisArg (optional)
: an object to use asthis
when executing the callback function.
Example
const numbers = [1, 2, 3, 4, 5];
const checkNumber = (number) => number > 3;
const index = numbers.findIndex(checkNumber);
console.log(index); // Output: 3
Output
The findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. If no elements in the array satisfy the condition, -1 is returned.
In the above example, the array contains the numbers 1
, 2
, 3
, 4
, and 5
. The checkNumber
function tests whether a given number is greater than 3
. Running numbers.findIndex(checkNumber)
returns 3
because the first number greater than 3
in the array is 4
.