Use reduce to group array items by property
const items = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'veg', name: 'carrot' }
];
const grouped = items.reduce((acc, item) => {
(acc[item.category] = acc[item.category] || []).push(item);
return acc;
}, {});const transactions = [
{ type: 'income', amount: 1000, month: 'Jan' },
{ type: 'expense', amount: 500, month: 'Jan' },
{ type: 'income', amount: 1500, month: 'Feb' },
{ type: 'expense', amount: 300, month: 'Feb' }
];
// Group by type
const byType = transactions.reduce((acc, t) => {
acc[t.type] = acc[t.type] || [];
acc[t.type].push(t);
return acc;
}, {});
console.log(byType);
// Group by multiple levels
const byMonthAndType = transactions.reduce((acc, t) => {
acc[t.month] = acc[t.month] || {};
acc[t.month][t.type] = acc[t.month][t.type] || [];
acc[t.month][t.type].push(t);
return acc;
}, {});
// Using Object.groupBy (ES2024)
const grouped = Object.groupBy(
transactions,
t => t.type
);const grouped = items.reduce((acc, item) => {
const key = item.category;
acc[key] = [...(acc[key] || []), item.name];
return acc;
}, {});const counts = items.reduce((acc, item) => {
acc[item.type] = (acc[item.type] || 0) + 1;
return acc;
}, {});Avoid nested loops for grouping
// DON'T DO THIS
var grouped = {};
for (var i = 0; i < items.length; i++) {
var key = items[i].category;
if (!grouped[key]) grouped[key] = [];
for (var j = 0; j < items.length; j++) {
if (items[j].category === key) {
grouped[key].push(items[j]);
}
}
}✓ Works in all modern browsers (ES5+ for reduce)