The findLastIndex() method in JavaScript is not a built-in method, but you can achieve similar functionality by using the reverse() method in conjunction with the findIndex() method. This combination allows you to find the index of the last element in an array that satisfies the provided testing function.
Syntax
array.reverse().findIndex(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to test each element of the array. It takes three arguments: element, index, and array. |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array findIndex() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Number | The index of the last element that satisfies the provided testing function, or -1 if no such element is found. |
Example 1: Finding the Index of the Last Even Number
This code demonstrates how to use the findIndex() method to find the index of the last even number in an array.
let numbers = [1, 3, 5, 7, 8, 9]; let lastEvenNumberIndex = numbers.findLastIndex(function(element) { return element % 2 === 0; }); console.log(lastEvenNumberIndex);
Output:
4
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let numbers = [1, 3, 5, 7, 8, 9]; let lastEvenNumberIndex = numbers.findLastIndex(element => element % 2 === 0); console.log(lastEvenNumberIndex);
Output:
4
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
97 | 97 | 104 | 83 | 15.4 |