Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Grouping Numbers by Even and Odd:
4.2.
JavaScript
4.3.
Categorizing Strings by Length:
4.4.
JavaScript
4.5.
Grouping Objects by a Property:
4.6.
JavaScript
4.7.
Advanced Grouping with a Composite Key:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
Can _.groupBy() handle complex grouping criteria?
5.2.
What happens to elements that don't match any group?
5.3.
Is _.groupBy() efficient for large datasets?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.groupBy() Method

Author Ravi Khorwal
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Grouping elements of a collection based on specific criteria is a common requirement in data manipulation. Lodash simplifies this task with its _.groupBy() method. This function organizes elements into groups according to the result of a provided function. 

Lodash _.groupBy() Method

This article explores _.groupBy(), detailing its syntax, use cases, and benefits, illustrated through examples and FAQs.

Why This Function is Used

The _.groupBy() function is essential for categorizing elements in a collection (such as an array or object) based on certain characteristics or conditions. It is widely used in scenarios involving data analysis, reporting, and UI rendering, where organizing data into meaningful groups facilitates better understanding and manipulation. This method streamlines the process of segregating data based on shared attributes, enhancing data readability and efficiency in processing.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.groupBy(collection, [iteratee=_.identity])

Parameters:

  • collection (Array|Object): The collection to iterate over.
     
  • [iteratee=_.identity] (Function): The iteratee to transform keys.

Return Value: 

(Object) - Returns the composed aggregate object.

Examples 

Grouping Numbers by Even and Odd:

  • JavaScript

JavaScript

var _ = require('lodash');

var numbers = [1, 2, 3, 4, 5, 6];

var groupedByEvenOdd = _.groupBy(numbers, num => num % 2 === 0 ? 'even' : 'odd');

console.log(groupedByEvenOdd);

Output:

 { 'odd': [1, 3, 5], 'even': [2, 4, 6] }


Demonstrates grouping numbers based on their parity.

Categorizing Strings by Length:

  • JavaScript

JavaScript

var words = ['one', 'two', 'three', 'four', 'five'];

var groupedByLength = _.groupBy(words, 'length');

console.log(groupedByLength);

 Output:

 { '3': ['one', 'two'], '4': ['four', 'five'], '5': ['three'] }


Shows how to group strings based on their length.

Grouping Objects by a Property:

  • JavaScript

JavaScript

var people = [{ 'name': 'Alice', 'age': 21 }, 

             { 'name': 'Bob', 'age': 21 },

             { 'name': 'Cindy', 'age': 25 }];

var groupedByAge = _.groupBy(people, 'age');

console.log(groupedByAge);

 Output:

 { '21': [{ 'name': 'Alice', 'age': 21 }, { 'name': 'Bob', 'age': 21 }], '25': [{ 'name': 'Cindy', 'age': 25 }] }


An example of grouping objects based on a shared property.

Advanced Grouping with a Composite Key:

  • JavaScript

JavaScript

var items = [{ 'type': 'fruit', 'name': 'apple' }, 

            { 'type': 'vegetable', 'name': 'carrot' },

            { 'type': 'fruit', 'name': 'banana' }];

var groupedByTypeAndName = _.groupBy(items, item => `${item.type}-${item.name}`);

console.log(groupedByTypeAndName);


Output: 

{ 'fruit-apple': [{...}], 'vegetable-carrot': [{...}], 'fruit-banana': [{...}] }


Demonstrates grouping based on a composite key created from multiple object properties.

Frequently Asked Questions 

Can _.groupBy() handle complex grouping criteria?

Yes, _.groupBy() can handle complex criteria by providing a custom iteratee function that returns the desired key based on which to group.

What happens to elements that don't match any group?

Elements that don't match any group are categorized under a key determined by the return value of the iteratee function. If the iteratee returns undefined, they are grouped under the undefined key.

Is _.groupBy() efficient for large datasets?

_.groupBy() is generally efficient, but performance may vary with the complexity of the iteratee function and the size of the dataset.

Conclusion

Lodash's _.groupBy() method is a powerful and flexible tool for organizing elements in a collection into groups based on specified criteria. It simplifies data categorization, aiding in efficient data analysis and manipulation across a wide range of applications.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.difference() Method
Next article
Lodash _.dropRightWhile() Method
Live masterclass