Group By

Group array items by a key using Object.groupBy or reduce.

Code

JavaScript
const items = [
  { type: "fruit", name: "apple" },
  { type: "veg", name: "carrot" },
  { type: "fruit", name: "banana" }
];

// Object.groupBy (ES2024)
const byType = Object.groupBy(items, (i) => i.type);

// Reduce (universal)
const byType2 = items.reduce((acc, item) => {
  const key = item.type;
  if (!acc[key]) acc[key] = [];
  acc[key].push(item);
  return acc;
}, {});

Line-by-line explanation

Expected output

{ fruit: [...], veg: [...] }

Related snippets

Related DuskTools