Open In App

Lodash _.findLast() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash _.findLast() method iterates over the elements in a collection from the right to the left. It is almost the same as _.find() method.

Syntax:

_.findLast(collection, predicate, fromIndex);

Parameters:

  • collection: It is the collection that the method iterates over.
  • predicate: It is the function that is invoked for every iteration.
  • fromIndex: It is the index of the array from where the search starts.

Return Value:

This method returns the element that matches, else undefined.

Example 1: In this example, we are getting the last existing element in an array which is satisfying the given condition in a function by the use of the lodash _.findLast() method.

javascript
// Requiring the lodash library 
const _ = require('lodash');

// Original array 
let users = ([3, 4, 5, 6]);

// Using the _.findLast() method
let found_elem = _.findLast(users, function (n) {
    return n % 2 == 1;
});

// Printing the output 
console.log(found_elem);

Output:

5

Example 2: In this example, we are getting the last existing element in an array which is satisfying the given condition in a function by the use of the lodash _.findLast() method.

javascript
// Requiring the lodash library 
const _ = require('lodash'); 
    
// Original array 
let user1 = ([3, 4, 5, 6, 9, 1, 7]);
let user2 = ([24, 14, 55, 36, 76]);

// Using the _.findLast() method
let found_elem = _.findLast(user1, function(n) {
  return n % 2 == 0;
});
let found_elem2 = _.findLast(user2, function(n) {
  return n % 2 == 1;
});

// Printing the output 
console.log(found_elem);
console.log(found_elem2);

Output:

6
55

Example 3: In this example, we are getting undefined as the last existing element in an array which is satisfying the given condition in a function is not present.

javascript
// Requiring the lodash library 
const _ = require('lodash');
// Original array 
let user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);

// Using the _.findLast() method
let found_elem = _.findLast(user1, function (n) {
    return n % 2 == 1;
});

// Printing the output 
console.log(found_elem);

Output:

undefined

Next Article

Similar Reads