Data manipulation and organization are common tasks in JavaScript programming. When dealing with arrays, grouping elements based on specific criteria can provide valuable insights and simplify subsequent operations. In this article, we'll explore the power of the groupBy
function in JavaScript, which enables effortless grouping of array elements. We'll walk through the implementation of the function and demonstrate its usage with practical examples.
Also you can see Lodash's popular implementation here.
This post is inspired by leedcode JavaScript 30 days Challenge day 24
Understanding the GroupBy Function
The groupBy
function enhances the functionality of JavaScript arrays by adding a convenient method that allows elements to be grouped based on a specified criterion. To give a concrete example of groupBy
in action:
const list = [
{ name: 'Ali', birthYear: 1991 },
{ name: 'Bosse', birthYear: 1982 },
{ name: 'Chukwu', birthYear: 1989 },
{ name: 'Jane', birthYear: 1994 },
{ name: 'Hassan', birthYear: 1995 }
]
const groupedByDecade = list.groupBy((person) => {
const decade = Math.floor(person.birthYear / 10) * 10;
return String(decade);
});
console.log(groupedByDecade);
/*
{
"1990": [
{ name: 'Ali', birthYear: 1991 },
{ name: 'Jane', birthYear: 1994 },
{ name: 'Hassan', birthYear: 2005 }
],
"1980": [
{ name: 'Bosse', birthYear: 1982 },
{ name: 'Chukwu', birthYear: 1989 }
]
}
*/
Here's the implementation of the groupBy
function:
// enabling any array to directly call the groupBy method
Array.prototype.groupBy = function(fn) {
const returnedObject = {}; //created to store the grouped elements
// iterates over each element of the array using the for...of loop.
for(const item of this){
//Determining the grouping key. Then the result is stored in the key variable.
const key = fn(item);
if(key in returnedObject){
//Checks if the key already exists as a property in the `returnedObject`
returnedObject[key].push(item);
} else {
returnedObject[key] = [item];
}
}
return returnedObject;
};
Practical Examples
Let's explore some practical examples to demonstrate the capabilities of the groupBy
function:
Example 1: Grouping numbers by parity(even or odd)
const numbers = [1, 2, 3, 4, 5, 6];
const groupedNumbers = numbers.groupBy(num => num % 2 === 0 ? 'even' : 'odd');
console.log(groupedNumbers);
Output:
{
even: [2, 4, 6],
odd: [1, 3, 5]
}
Example 2: Grouping objects by property
const students = [
{ name: 'Ali', grade: 'A' },
{ name: 'Bosse', grade: 'B' },
{ name: 'Chukwu', grade: 'A' },
{ name: 'Dan', grade: 'C' }
];
const groupedStudents = students.groupBy(student => student.grade);
console.log(groupedStudents);
Output:
{
A: [
{ name: 'Ali', grade: 'A' },
{ name: 'Chukwu', grade: 'A' }
],
B: [
{ name: 'Bosse', grade: 'B' }
],
C: [
{ name: 'Dan', grade: 'C' }
]
}
Conclusion
The groupBy
function in JavaScript is a powerful tool that simplifies data grouping in arrays. By leveraging this utility, developers can easily categorize and organize elements based on custom criteria. The ability to group data efficiently opens the door to numerous possibilities for data analysis, transformation, and further processing. Incorporate the groupBy
function into your
Top comments (5)
i constantly use groupBy and indexBy to avoid extra pooling. recently I began however to use an implementation using js's Map class. because for this usecase it is supposed to be faster than an objects internal subclassing for adding all the properties.
Thanks for sharing practical examples of the groupBy function. It makes understanding and implementing it much easier. Keep up the good work!
Thank you chief. I appreciate
Thank you for your excitation.
The examples would be better readable if you apply a language specifier after the backticks:
see editor guidelines for more details
Thank you so much for the observation