The Wayback Machine - https://web.archive.org/web/20240118171335/https://www.geeksforgeeks.org/lodash-_-groupby-method/
Open In App
Related Articles

Lodash _.groupBy() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Lodash _.groupBy() method creates an object composed of keys generated from the results of running each element of collection through the iterate function. The order of the grouped values is determined by the order they occur in the collection. Also, the corresponding value of each key is an array of elements responsible for generating the 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 ] }

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 24 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials