Find Last Matching Value

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will delve into JavaScript programming and explore the concept of finding the last matching value in an array. This lab provides an opportunity to enhance your understanding of JavaScript array methods and functional programming techniques. By the end of this lab, you will have a solid understanding of how to use the Array.prototype.filter() and Array.prototype.pop() methods to find the last element that meets a certain condition.


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/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28306{{"`Find Last Matching Value`"}} javascript/comp_ops -.-> lab-28306{{"`Find Last Matching Value`"}} javascript/higher_funcs -.-> lab-28306{{"`Find Last Matching Value`"}} end

JavaScript Function for Finding the Last Matching Value

To find the last element in an array that satisfies a given condition, use the following JavaScript function:

const findLast = (arr, fn) => arr.filter(fn).pop();

To use this function, pass in the array you want to search and a function that returns a truthy value for the elements you want to match.

For example, findLast([1, 2, 3, 4], n => n % 2 === 1); will return 3, as it finds the last odd number in the array.

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

Summary

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

Other JavaScript Tutorials you may like