- Published
- Author
- Sudeep Hipparge
JavaScript: Object.groupBy()
Grouping data used to be messy β relying on Array.reduce() with verbose logic. But JavaScript's new Object.groupBy() method has made things incredibly elegant and easy!
With just one line, you can group array items based on any property.
Itβs clean, readable, and production-friendly.
π Example:
π‘ Output:
β Cleaner. β Less boilerplate. β Much easier to read.
#CCT1JMA0Z #WebDevelopment
Grouping data used to be messy β relying on Array.reduce() with verbose logic. But JavaScript's new Object.groupBy() method has made things incredibly elegant and easy!
With just one line, you can group array items based on any property.
Itβs clean, readable, and production-friendly.
π Example:
Code
const products = [
{ name: "T-shirt", category: "clothes", price: 50 },
{ name: "Apple", category: "food", price: 5 },
{ name: "Shoes", category: "clothes", price: 35 },
{ name: "Orange", category: "food", price: 7.5 },
{ name: "Blueberry", category: "food", price: 4.5 }
];
const grouped = Object.groupBy(products, product => product.category);
console.log(grouped);π‘ Output:
Code
{
clothes: [
{ name: "T-shirt", category: "clothes", price: 50 },
{ name: "Shoes", category: "clothes", price: 35 }
],
food: [
{ name: "Apple", category: "food", price: 5 },
{ name: "Orange", category: "food", price: 7.5 },
{ name: "Blueberry", category: "food", price: 4.5 }
]
}β Cleaner. β Less boilerplate. β Much easier to read.
#CCT1JMA0Z #WebDevelopment