Lodash _.groupBy() Method
Last Updated :
09 Jan, 2025
Lodash's _.groupBy() method groups elements of a collection into an object, using the results of an iterated function as keys, with corresponding arrays of elements that generate each key.
Syntax:
_.groupBy(collection, [iteratee]);
Parameters:
- Collection: It is the collection that the method iterates over.
- Iteratee: It is the function that is invoked for every element in the array.
Return Value: This method returns the composed aggregate object.
Example 1: In this example, we are composing an array-by-length function where the array is grouped by the length of the strings.
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = (['eight', 'nine', 'four', 'seven']);
// Using of _.groupBy() method
// with the `_.property` iteratee shorthand
let grouped_data = _.groupBy(users, 'length')
console.log(grouped_data);
Output:
{ '4': [ 'nine', 'four' ], '5': [ 'eight', 'seven' ]}
Example 2: In this example, we are composing an array by in which array is grouped according to the Math.floor function.
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = (['one', 'two', 'three', 'four']);
let obj = ([3.1, 1.2, 3.3]);
// Using the _.groupBy() method
// with the `_.property` iteratee shorthand
let grouped_data = _.groupBy(users, 'length')
let grouped_data2 = _.groupBy(obj, Math.floor)
// Printing the output
console.log(grouped_data, grouped_data2);
Output:
{ '3': [ 'one', 'two' ], '4': [ 'four' ], '5': [ 'three' ] }
{ '1': [ 1.2 ], '3': [ 3.1, 3.3 ] }
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics