Find Last Matching Index

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of finding the last matching index of an element in an array using JavaScript. We will learn how to use the Array.prototype.map() and Array.prototype.filter() methods to filter out the elements for which the provided function returns falsy values, and Array.prototype.pop() to get the last element in the filtered array. By the end of this lab, you will be able to efficiently find the last matching index of an element in an array using JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28304{{"`Find Last Matching Index`"}} javascript/data_types -.-> lab-28304{{"`Find Last Matching Index`"}} javascript/arith_ops -.-> lab-28304{{"`Find Last Matching Index`"}} javascript/comp_ops -.-> lab-28304{{"`Find Last Matching Index`"}} javascript/higher_funcs -.-> lab-28304{{"`Find Last Matching Index`"}} end

How to Find the Index of the Last Matching Element in an Array Using JavaScript

To find the index of the last element that matches a certain condition in a JavaScript array, use the findLastIndex function. Here's how to use it:

const findLastIndex = (arr, fn) =>
  (arr
    .map((val, i) => [i, val])
    .filter(([i, val]) => fn(val, i, arr))
    .pop() || [-1])[0];

The findLastIndex function takes two arguments: the array to search and a function to test each element. Here's how it works:

  1. Use Array.prototype.map() to create a new array of [index, value] pairs.
  2. Use Array.prototype.filter() to remove elements from the array that don't match the condition provided by the fn function.
  3. Use Array.prototype.pop() to get the last element in the filtered array.
  4. If the filtered array is empty, return -1.

Here's an example of how to use findLastIndex:

findLastIndex([1, 2, 3, 4], (n) => n % 2 === 1); // 2 (index of the value 3)
findLastIndex([1, 2, 3, 4], (n) => n === 5); // -1 (default value when not found)

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Find Last Matching Index lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like