Grouping Array Elements by Property
You'll learn how to organize an array of objects into categories using reduce, creating a structured lookup object where each key represents a group.
The Core Idea
Imagine you have a pile of colored blocks mixed together, and you want to organize them into separate containers by color. Grouping array elements works the same way: you take an array of objects, examine a specific property on each object (like a "category" field), and sort them into groups within a single organizing object.
Instead of having a flat array, you end up with an object where each key is a category name, and each value is an array of items belonging to that category.
How It Works with Reduce
reduce is perfect for this because:
- The accumulator becomes your organizing object (the collection of containers)
- For each item, you check if its category already has a container (array)
- If not, create an empty array for that category
- Add the item to its category's array
Example Pattern
const products = [
{ name: 'Apple', category: 'fruit' },
{ name: 'Carrot', category: 'vegetable' },
{ name: 'Banana', category: 'fruit' },
{ name: 'Broccoli', category: 'vegetable' }
];
const grouped = products.reduce((acc, item) => {
const category = item.category;
if (!acc[category]) {
acc[category] = [];
}
acc[category].push(item);
return acc;
}, {});
// Result:
// {
// fruit: [{ name: 'Apple', ... }, { name: 'Banana', ... }],
// vegetable: [{ name: 'Carrot', ... }, { name: 'Broccoli', ... }]
// }
Key Takeaway: Use reduce with an empty object as the initial value to group array elements by a shared property, building a structured lookup object organized by categories.