JavaScript Snippet

Group an Array by a Key

Difficulty: Medium

Grouping records by a derived key is one of the most common data-shaping tasks in JavaScript: bucketing users by role, orders by status, logs by date. This snippet shows a portable `Map`-based helper, a plain-object variant, and the modern `Object.groupBy` API that landed in Node 22 and recent browsers. It also covers the multi-key composite-key trick for grouping by tuples like `[city, role]`.

Code Snippets
/

Group an Array by a Key

Group an Array by a Key

Grouping records by a derived key is one of the most common data-shaping tasks in JavaScript: bucketing users by role, orders by status, logs by date. This snippet shows a portable `Map`-based helper, a plain-object variant, and the modern `Object.groupBy` API that landed in Node 22 and recent browsers. It also covers the multi-key composite-key trick for grouping by tuples like `[city, role]`.

JavaScript
Medium
4 snippets
arrays
utility
array-manipulation-patterns
hash-table

334 views

5

The function walks the input once and accumulates each item into a Map keyed by the result of keyFn(item). Using a Map instead of a plain object preserves insertion order, supports any key type (numbers, booleans, even objects), and avoids the __proto__ / constructor collision pitfalls of object-as-dictionary code. The whole pass is O(n) time and O(n) space, with one dictionary lookup and one push per element. Reach for this helper any time you need to bucket records before rendering a grouped list, computing per-group totals, or feeding a chart.