javascript / intermediate
Snippet
Grouping Collections with Object.groupBy
The Object.groupBy static method groups elements of an iterable according to a string value returned by a callback function. This replaces manual reduce() implementations for categorizing data.
snippet.js
1
2
3
4
5
6
7
8
9
10
const orders = [{ id: 1, status: 'pending', total: 50 },{ id: 2, status: 'shipped', total: 120 },{ id: 3, status: 'pending', total: 80 }];const groupedByStatus = Object.groupBy(orders, (order) => order.status);console.log(groupedByStatus.pending);// Output: [{ id: 1, ... }, { id: 3, ... }]
nodejs
Breakdown
1
Object.groupBy(orders, ...)
Calls the static method to create a null-prototype object with status keys.
2
(order) => order.status
The callback determines the key under which each element is stored.