Array.findIndex()
The Array.findIndex()
method in JavaScript is used to find the index of the first element in an array that satisfies a provided testing function. If no elements satisfy the testing function, it returns -1
.
Syntax
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function to execute on each element in the array. It should return a truthy value for the element to be considered a match. |
thisArg (optional) | A value to use as this when executing callbackFn . |
Return Value
The findIndex()
method returns the index of the first element in the array that satisfies the callbackFn
. If no such element is found, it returns -1
.
Examples
1. Finding the Index of an Element
This example demonstrates how to use findIndex()
to locate the index of the first even number in an array.
const numbers = [1, 3, 7, 8, 10];
const index = numbers.findIndex((num) => num % 2 === 0);
console.log(index);
Output
3
The first even number is 8
, located at index 3
.
2. Using thisArg
with findIndex()
This example demonstrates the use of the optional thisArg
parameter to define the this
context for the callback function.
const threshold = { limit: 5 };
const numbers = [1, 6, 8, 3, 4];
const index = numbers.findIndex(function (num) {
return num > this.limit;
}, threshold);
console.log(index);
Output
1
The first element greater than 5
is 6
, located at index 1
. The thisArg
sets this.limit
to 5
.
3. No Matching Element
When no element satisfies the condition, findIndex()
returns -1
.
const numbers = [1, 3, 5, 7];
const index = numbers.findIndex((num) => num % 2 === 0);
console.log(index);
Output
-1
There are no even numbers in the array, so the method returns -1
.
4. Using findIndex()
with Objects
The findIndex()
method can also be used to find the index of an object in an array based on a condition.
const users = [
{ id: 1, name: "Akash" },
{ id: 2, name: "Bhairav" },
{ id: 3, name: "Charlie" }
];
const index = users.findIndex((user) => user.name === "Bhairav");
console.log(index);
Output
1
The object representing Bhairav
is located at index 1
.