It baffles me every time I run into a JavaScript method I haven't encountered in my 10+ years as a web developer. I only very recently ran into the Object.groupBy() method.
What is Object.groupBy()?
The Object.groupBy() function is a utility in JavaScript used to group elements of an array or collection based on a defined parameter. It takes two arguments: the collection to group and a callback function that determines the grouping logic.
How does it work?
Let's dive into an example:
Suppose you have an array of objects containing some very important business data.
const species = [
{ name: "Human", language: "Galactic Basic", classification: "mammal" },
{ name: "Wookiee", language: "Shyriiwook", classification: "mammal" },
{ name: "Vulptereen", language: "vulpterish", classification: "unknown" },
{ name: "Xexto", language: "Xextese", classification: "unknown" },
{ name: "Toong", language: "Tundan", classification: "unknown" },
];
Now, let's group this very important business data by one of the values within these objects.
Object.groupBy(species, ({ classification }) => classification);
And the perfectly grouped object that is returned:
{
"mammal": [
{ "name": "Human", "language": "Galactic Basic", "classification": "mammal"},
{ "name": "Wookiee", "language": "Shyriiwook", "classification": "mammal"}
],
"unknown": [
{ "name": "Vulptereen", "language": "vulpterish", "classification": "unknown"},
{ "name": "Xexto", "language": "Xextese", "classification": "unknown"},
{ "name": "Toong", "language": "Tundan", "classification": "unknown"}
]
}
Use Cases
There are lots of practical use cases for this method. Take performance into account when thinking about leveraging this secret. Object.groupBy() may not be your best bet when parsing massive datasets.
- Grouping products by category on an e-commerce site.
- Organizing tasks by priority in a to-do list application.
- Organizing restaurant menu items by course (appetizers, main dishes, deserts, drinks, etc.)
Object.groupBy() is a powerful function for grouping data in JavaScript. It simplifies the process of organizing information based on specific criteria, making it a great tool for developers dealing with diverse datasets.
Have you explored this method? Comment below, show us some cool stuff you've done that leverages it! 🤘
A quick note and thanks to @oculus42 for pointing out in the comments below:
Object.groupBy and Map.groupBy are not yet part of the specification, but you can check out the TC39 GroupBy proposal for more details. At Stage 3, it looks like it will likely make its way into ES2024.
It's not currently supported in all browsers, as it was only added to Chrome in September and Firefox last month. Clicking the browser versions in the MDN Browser Compatibility table will tell you when that version was released.