What Does Lodash groupBy Return?
The _.groupBy method in the Lodash JavaScript library
returns a standard, composed JavaScript object. This article breaks down
the exact structure of this returned object, explaining how Lodash
assigns keys based on an iteratee criterion and maps them to arrays
containing the grouped elements from the original collection.
The Return Value Structure
When you invoke
_.groupBy(collection, [iteratee=_.identity]), Lodash
iterates over the input collection and constructs a plain JavaScript
Object.
The structure of the resulting object consists of:
- Keys: Strings generated by running each element of
the collection through the provided
iterateefunction (or property shorthand). Even if the iteratee returns a number or boolean, JavaScript converts object keys into strings. - Values: Arrays of the original elements from the collection that produced the corresponding key. The original order of elements within each array is preserved.
Practical Example
Consider an array of user objects grouped by their role
property:
const users = [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'admin' }
];
const result = _.groupBy(users, 'role');The resulting result variable is a plain object with the
following structure:
{
"admin": [
{ name: 'Alice', role: 'admin' },
{ name: 'Charlie', role: 'admin' }
],
"user": [
{ name: 'Bob', role: 'user' }
]
}Key Behaviors
- Empty Collections: If the input collection is
null,undefined, or empty ([]),_.groupByreturns an empty object ({}). - Custom Iteratee Functions: If an iteratee function is supplied instead of a string property, the returned object's keys will be the values returned by that function:
const numbers = [6.1, 4.2, 6.3];
const result = _.groupBy(numbers, Math.floor);
// Returns: { '4': [4.2], '6': [6.1, 6.3] }The returned entity is always a mutable, plain object
({}) whose values are guaranteed to be standard JavaScript
arrays.