Horje
JavaScript Array findLastIndex() Method

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

// Declare an array
const arr1 = [1, 45, 69, 84];
  
// Declare an array
const arr2 = [9, -2, 6.8];
  
// Declare a function called that 
// takes an element as a parameter
// and returns true if the element
// is greater than 19
const isLargeNumber = (element) => element > 19;
  
// Call the findLastIndex method on 
// the arr1 array and pass in the 
// isLargeNumber function as a parameter
console.log(arr1.findLastIndex(isLargeNumber));
  
// Call the findLastIndex method on 
// the arr2 array and pass in the
// isLargeNumber function as a parameter
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

Output

9

Supported Browsers:

  • Google Chrome 97
  • Edge 97
  • Firefox 104
  • Apple Safari 15.4
  • Opera 83



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Next.js Disabling ETag Generation Next.js Disabling ETag Generation
Difference between ScriptManager and ScriptManagerProxy Difference between ScriptManager and ScriptManagerProxy
How to search a vertical tab character with JavaScript RegExp ? How to search a vertical tab character with JavaScript RegExp ?
What is TypeScript Definition Manager and Why Do We Need It? What is TypeScript Definition Manager and Why Do We Need It?
How to create a GUID / UUID in JavaScript ? How to create a GUID / UUID in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12