javascript / intermediate
Snippet
Data Grouping with Array.prototype.reduce()
The reduce method is a versatile tool for transforming an array into a single object. By initializing with an empty object, we can iterate through the list and dynamically build a categorized map of items.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const inventory = [{ name: 'Apples', type: 'fruit' },{ name: 'Carrots', type: 'vegetable' },{ name: 'Bananas', type: 'fruit' }];const grouped = inventory.reduce((acc, item) => {const key = item.type;if (!acc[key]) acc[key] = [];acc[key].push(item.name);return acc;}, {});
Breakdown
1
inventory.reduce((acc, item) => { ... }, {});
Starts the reduction with an empty object as the accumulator.
2
const key = item.type;
Determines the category key for the current item.
3
acc[key].push(item.name);
Appends the item's name to the corresponding category array.