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
- 1.Object.groupBy groups by return value of callback.
- 2.reduce builds object with arrays per key.
- 3.Check if key exists before pushing.
Expected output
{ fruit: [...], veg: [...] }