Back to Home
Arrays

How to Group Array Items

Use reduce to group array items by property

Quick Answer (2024 ES6+ Way)

javascript
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;
}, {});

Live Example

javascript
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
);

Common Variations

Group and Transform
javascript
const grouped = items.reduce((acc, item) => {
  const key = item.category;
  acc[key] = [...(acc[key] || []), item.name];
  return acc;
}, {});
Count by Group
javascript
const counts = items.reduce((acc, item) => {
  acc[item.type] = (acc[item.type] || 0) + 1;
  return acc;
}, {});

❌ Don't Do This (Outdated Way)

Avoid nested loops for grouping

javascript
// 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]);
    }
  }
}

Browser Support

Works in all modern browsers (ES5+ for reduce)

#array#group#categorize