Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.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: This method accepts three parameters as mentioned above and described below:
- 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:
// Requiring the lodash library const _ = require( "lodash" ); // Original array var 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:
// Requiring the lodash library const _ = require( "lodash" ); // Original array var user1 = ([3, 4, 5, 6, 9, 1, 7]); var 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:
// Requiring the lodash library const _ = require( "lodash" ); // Original array var 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