JavaScript, the language that powers the dynamic and interactive web, is constantly evolving to make developers' lives easier. This blog is the introduction of two powerful methods for grouping data: Object.groupBy
and Map.groupBy
. π€―
These methods promise to simplify grouping operations, eliminating the need for external dependencies and enhancing the overall development experience.
What's the Buzz About?
groupBy
methods aim to streamline process of grouping data, offering a native and efficient solution for grouping objects and maps.
Object.groupBy
Let's start by exploring Object.groupBy
. This method is designed to work with arrays of objects, making it a valuable addition for handling complex datasets.
const employees = [
{ name: 'Shameel', department: 'HR' },
{ name: 'Uddin', department: 'Engineering' },
{ name: 'Syed', department: 'HR' },
];
// Grouping employees by department using Object.groupBy
const groupedByDepartment = Object.groupBy(employees,({department})=>department)
console.log(groupedByDepartment);
In this example, employees
are grouped by their respective departments, resulting in a clear and concise structure.
Result:
{
"HR": [
{
"name": "Shameel",
"department": "HR"
},
{
"name": "Syed",
"department": "HR"
}
],
"Engineering": [
{
"name": "Uddin",
"department": "Engineering"
}
]
}
Map.groupBy
The Map.groupBy
method extends the grouping capabilities to Map objects, providing a versatile solution for scenarios where a Map structure is preferred.
const inventory = [
{ name: 'π₯¦ broccoli', type: 'vegetables', quantity: 9 },
{ name: 'π bananas', type: 'fruit', quantity: 5 },
{ name: 'π goat', type: 'meat', quantity: 23 },
{ name: 'π cherries', type: 'fruit', quantity: 12 },
{ name: 'π fish', type: 'meat', quantity: 22 },
];
const restock = { restock: true };
const sufficient = { restock: false };
// Using Map.groupBy to categorize items based on quantity
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient
);
// Displaying items that need restocking
console.log(result.get(restock));
Here, orders
are grouped by the product they contain, showcasing the flexibility and expressiveness of the Map.groupBy
method.
Conclusion
The beauty of these new methods lies in their simplicity. They abstract away the complexity of manual grouping, providing a clean and expressive syntax. No more lengthy code or external dependencies β just pure JavaScript magic!
Happy coding! ππ»β¨
Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123