Syntax, Parameter and Return Value
Syntax:
_.findLastKey(object, [predicate=_.identity])
Parameters:
-
object (Object): The object to inspect.
- [predicate=_.identity] (Function): The function invoked per iteration.
Return Value:
(string|undefined) - Returns the key of the matched element, else undefined.
Examples
Finding the Last Key Based on a Condition:
JavaScript
var _ = require('lodash');
var users = {
'barney': { 'age': 36, 'active': false },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
var key = _.findLastKey(users, function(o) { return o.active; });
console.log(key);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'pebbles'
Demonstrates finding the key of the last user who is active.
Using a Shorthand with Property Value:
JavaScript
var key = _.findLastKey(users, { 'age': 36, 'active': false });
console.log(key);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'barney'
Shows how to use object literal shorthand to find the last matching key.
Using a Property Name Shorthand:
JavaScript
var key = _.findLastKey(users, 'active');
console.log(key);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'pebbles'
An example of using property name shorthand to find the key of the last active user.
Matching Against a Property Value:
JavaScript
var key = _.findLastKey(users, ['active', false]);
console.log(key);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'fred'
Demonstrates finding the key of the last user where the 'active' property is false.
Frequently Asked Questions
How does _.findLastKey() differ from _.findKey()?
_.findKey() returns the key of the first element that satisfies the predicate, while _.findLastKey() returns the key of the last element that satisfies the predicate.
What happens if no element satisfies the predicate?
If no element satisfies the predicate, _.findLastKey() returns undefined.
Can _.findLastKey() be used with arrays?
While _.findLastKey() is primarily designed for objects, it can be used with arrays. However, since array indices are less informative than object keys, array-specific methods are usually more suitable for arrays.
Conclusion
Lodash's _.findLastKey() method offers an effective way to search for the last key in an object that meets a specific condition. It is particularly useful for ordered objects or when the most recent (last) match based on certain criteria is required.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.