Array.findLastIndex()
The Array.findLastIndex()
method in JavaScript returns the index of the last element in the array that satisfies the provided testing function. If no elements satisfy the testing function, it returns -1
.
Syntax
</>
Copy
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function that is called for every element in the array, in reverse order, until it returns a truthy value. It takes three arguments: element (current array element), index (index of the element), and array (the array itself). |
thisArg | Optional. A value to use as this when executing callbackFn . |
Return Value
The findLastIndex()
method returns the index of the last element in the array that satisfies the callbackFn
. If no such element is found, it returns -1
.
Examples
1. Finding the Last Even Number
This example finds the last even number in an array and returns its index.
</>
Copy
const numbers = [5, 12, 8, 130, 44];
const lastEvenIndex = numbers.findLastIndex(num => num % 2 === 0);
console.log(lastEvenIndex);
Output
4
- The last even number is
44
, located at index4
.
2. Finding Based on Object Property
This example finds the index of the last person over 30 in an array of objects.
</>
Copy
const people = [
{ name: 'Akash', age: 25 },
{ name: 'Bhairav', age: 35 },
{ name: 'Charlie', age: 40 }
];
const lastOver30Index = people.findLastIndex(person => person.age > 30);
console.log(lastOver30Index);
Output
2
- The last person over 30 is
Charlie
, located at index2
.
3. Using thisArg
The thisArg
parameter is used to provide a custom context for the callback function.
</>
Copy
const numbers = [1, 2, 3, 4, 5];
const context = { threshold: 3 };
const lastAboveThreshold = numbers.findLastIndex(function(num) {
return num > this.threshold;
}, context);
console.log(lastAboveThreshold);
Output
4
- The custom context sets a threshold of
3
, and the last number greater than3
is5
, located at index4
.
4. No Matching Element
When no elements satisfy the callbackFn
, -1
is returned.
</>
Copy
const numbers = [1, 2, 3];
const index = numbers.findLastIndex(num => num > 5);
console.log(index);
Output
-1
Since no numbers are greater than 5
, findLastIndex()
returns -1
.