javascript / intermediate
Snippet
Grouping Array Elements
Object.groupBy() is a static method that groups elements of an iterable based on the string value returned by a callback function. It returns a null-prototype object with separate properties for each group.
snippet.js
1
2
3
4
5
6
7
8
const inventory = [{ name: 'Apple', type: 'fruit' },{ name: 'Carrot', type: 'vegetable' },{ name: 'Banana', type: 'fruit' }];const grouped = Object.groupBy(inventory, item => item.type);console.log(grouped.fruit);
nodejs
Breakdown
1
Object.groupBy(inventory, item => item.type);
Groups the inventory items using the 'type' property as the key.
2
grouped.fruit
Accesses the array of items that were categorized under the 'fruit' key.