patternjavascriptTip
Object.groupBy (ES2024) for grouping arrays without reduce boilerplate
Viewed 0 times
ES2024 — Node.js 21+, Chrome 117+
Object.groupByMap.groupBygroup byES2024array grouping
Problem
Grouping an array of objects by a property requires a verbose reduce or a utility library. This pattern was one of Lodash's most-used features for years.
Solution
Object.groupBy(iterable, keyFn) groups elements by the string key returned by the callback.
const byDept = Object.groupBy(people, p => p.dept);
// { eng: [Alice, Carol], hr: [Bob] }
// Map.groupBy preserves non-string keys
const byLength = Map.groupBy(words, w => w.length);
const byDept = Object.groupBy(people, p => p.dept);
// { eng: [Alice, Carol], hr: [Bob] }
// Map.groupBy preserves non-string keys
const byLength = Map.groupBy(words, w => w.length);
Why
groupBy is one of the most requested array utilities. The native version is optimised and eliminates a Lodash dependency for this single operation.
Gotchas
- Object.groupBy returns a null-prototype object — no inherited Object methods like .hasOwnProperty
- A callback returning undefined groups elements under the string key 'undefined'
- Map.groupBy is the sibling for non-string keys
- Available in Node.js 21+ and Chrome 117+
Code Snippets
Object.groupBy and Map.groupBy
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 200 },
];
const byType = Object.groupBy(inventory, item => item.type);
// { vegetables: [...], fruit: [...] }
const byInStock = Map.groupBy(inventory, item => item.quantity > 0);Revisions (0)
No revisions yet.