Group array elements into an object based on a callback function using Object.groupBy()
.
Explanation
Object.groupBy(array, callback)
: Groups array elements into an object where keys are determined by the callback function.- The callback function receives each element and should return a string key for grouping.
- Returns an object where each key contains an array of elements that returned that key.
- More efficient and readable than using
reduce()
for grouping operations.
Usage
To group array elements by a specific property or condition:
const products = [
{ name: 'Laptop', category: 'Electronics', price: 999 },
{ name: 'Shirt', category: 'Clothing', price: 29 },
{ name: 'Phone', category: 'Electronics', price: 699 },
{ name: 'Jeans', category: 'Clothing', price: 79 }
];
// Group by category
const byCategory = Object.groupBy(products, item => item.category);
console.log(byCategory);
// Expected output: {
// Electronics: [{ name: 'Laptop', ... }, { name: 'Phone', ... }],
// Clothing: [{ name: 'Shirt', ... }, { name: 'Jeans', ... }]
// }
// Group by price range
const byPriceRange = Object.groupBy(products, item =>
item.price > 100 ? 'expensive' : 'affordable'
);