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:

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

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.