How Lodash maxBy Extracts Properties
The Lodash _.maxBy method computes the maximum value of
an array based on criteria generated by an iteratee. When a property
name or path is supplied instead of a custom callback function, Lodash
automatically resolves it using its built-in _.property
iteratee shorthand. This article breaks down how _.maxBy
extracts properties from objects, how the underlying
baseIteratee works, and how to utilize different extractor
patterns in your code.
The Property Extractor:
_.property
When you invoke _.maxBy(array, [iteratee=_.identity])
and pass a string as the second argument, Lodash does not evaluate the
string directly. Instead, it converts the string into a getter function
via _.property(path).
This extractor navigates each object in the collection, retrieves the
value associated with the specified key, and uses that value to perform
numerical comparisons using standard greater-than (>)
logic.
const _ = require('lodash');
const users = [
{ name: 'Alice', score: 84 },
{ name: 'Bob', score: 95 },
{ name: 'Charlie', score: 90 }
];
// Lodash converts 'score' into _.property('score')
const topUser = _.maxBy(users, 'score');
// Output: { name: 'Bob', score: 95 }How Lodash Resolves Iteratees Internally
The property extraction mechanism in _.maxBy is powered
by an internal Lodash helper called baseIteratee. Whenever
a method in Lodash accepts an iteratee argument,
baseIteratee inspects the data type:
- String or Array Path: Converts the argument into
_.property(path), creating a function that retrieves shallow or deeply nested values. - Object: Converts the argument into
_.matches(source), checking for matching key-value pairs. - Function: Uses the custom function directly without modification.
- Undefined/Null: Defaults to
_.identity, which evaluates the elements themselves.
Because of this system, passing a string like 'score' to
_.maxBy(users, 'score') is functionally identical to
writing _.maxBy(users, _.property('score')) or
_.maxBy(users, o => o.score).
Deep Path Property Extraction
The _.property extractor supports nested paths. You can
pass dot-notation strings or arrays of keys to extract properties
located deep within nested object structures without risking
TypeError: Cannot read properties of undefined errors.
const inventory = [
{ item: 'Laptop', pricing: { retail: 1200 } },
{ item: 'Monitor', pricing: { retail: 300 } },
{ item: 'Keyboard', pricing: { retail: 100 } }
];
// Dot notation
const priciestItem = _.maxBy(inventory, 'pricing.retail');
// Array path notation
const alsoPriciestItem = _.maxBy(inventory, ['pricing', 'retail']);In both cases, Lodash’s deep property getter safely traverses the
structure. If an object lacks the specified path, the extractor returns
undefined, which is ignored during ranking comparisons.