In JavaScript, It is a common use case to find an element from an array based on filter logic. Filter logic is a Lambda expression.

Prior to ES14, Array has two methods to find an element and index position

  • find() method : Iterates elements from Start, find an matching element, return it, else returns undefined
  • findIndex() method : Iterates elements from Start, find an matching element, return its index if found, else return -1

The above methods, find an element and index position based on condition with iteration starts from Beginning

const numbers = [2, 5, 7, 10, 13]

//find returns element for matching element, Iterates starts from Beginnning
const result = numbers.find(item => item < 10)
console.log(result) // 👉🏼 2

//findIndex returns index position for matching element,
//Iterates from Starting position
const result = numbers.findIndex(item => item < 10)
console.log(result) // 👉🏼 0

Array findLast and findLastIndex methods with examples

ES14 introduced Array new methods to find an element, traversed from last position.

--- title: W3schoolsio ES14 Array Last Methods --- %%{init: {"flowchart": {"htmlLabels": false}} }%% flowchart TD markdown["`**ES14(ECMAScript2023)**`"] array["`**Array.prototype**`"] findlast["`**findLast** Method`"] findlastindex["`**findLastIndex** Method`"] markdown --> array array --> findlast array --> findlastindex

ES2023(ES14) introduced two methods to Array and TypedArray to find an element from end position

  • findLast() method:

    • Iterates elements from Array end,
      • returns matching element if condition satisfies,
      • else undefined returned
  • findLastIndex() :

    • Iterates array elements from end,
      • returns matching element index if condition is true ,
      • else return -1

Here is an example

const numbers = [2, 5, 7, 10, 13]

//findLast returns element for matching element, iterates starts from End position
const result = numbers.findLast(item => item < 10)
console.log(result) // 👉🏼 7

//findLastIndex returns index position for matching element,
// Iterates from End position
const result = numbers.findLastIndex(item => item < 10)
console.log(result) // 👉🏼 2

Conclusion

  • find, findIndex and findLast, findLastIndex methods does the same thing for matching element and index based on condition. The difference is last methods iterate in reverse order(from last)