Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Array findLastIndex() Method

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments