JavaScript Array findLastIndex() Method
Last Updated :
22 Mar, 2023
The Javascript findLastIndex() method is used to find the index of the last element in an array that matches the specified condition. It works by iterating over the array from the end to the beginning and returning the index of the first element that satisfies the condition specified in a callback function. If no element matches the condition, the method returns -1. This method is useful when you need to find the last occurrence of a specific value in an array.
Syntax:
array.findLastIndex( element );
Parameters: This method accepts a single parameter that is described below:
- element: This parameter holds the current element.
Return Value: The index of the last (highest-index) element in the array that passes the test. Otherwise, -1 if no matching element is found.
Example 1:
Javascript
const arr1 = [1, 45, 69, 84];
const arr2 = [9, -2, 6.8];
const isLargeNumber = (element) => element > 19;
console.log(arr1.findLastIndex(isLargeNumber));
console.log(arr2.findLastIndex(isLargeNumber));
|
Output:
3
-1
Example 2:
Javascript
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const isEven = (num) => num % 2 === 0;
const lastIndex = arr.findLastIndex(isEven);
console.log(lastIndex);
|
Output
9
Supported Browsers:
- Google Chrome 97
- Edge 97
- Firefox 104
- Apple Safari 15.4
- Opera 83
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...