Array grouping
Object.groupBy() and Map.groupBy() organize items into groups based on the value returned by a callback. They are useful for summaries, dashboards, and grouped rendering.
Overview
Object.groupBy() and Map.groupBy() organize items into groups based on the value returned by a callback. They are useful for summaries, dashboards, and grouped rendering.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 117 | 117 | 119 | 17.4 | 117 | 17.4 | |
| Built-in object | ||||||
| The Object.groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function. The returned object has separate properties for each group, containing arrays with the elements in the group. | 117 | 117 | 119 | 17.4 | 117 | 17.4 |
- This feature was removed in a later browser version (17.4)
- Previously available under a different name: Array.prototype.groupToMap (16.4)
- This feature was removed in a later browser version (17.4)
- Previously available under a different name: Array.prototype.groupToMap (16.4)
- This feature was removed in a later browser version (17.4)
- Previously available under a different name: Array.prototype.groupToMap (16.4)
- This feature was removed in a later browser version (17.4)
- Previously available under a different name: Array.prototype.groupToMap (16.4)
Syntax
const products = [
{ name: 'apple', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'banana', type: 'fruit' },
{ name: 'spinach', type: 'vegetable' },
];
const grouped = Object.groupBy(products, p => p.type);
// {
// 'fruit': [{ name: 'apple', ... }, { name: 'banana', ... }],
// 'vegetable': [{ name: 'carrot', ... }, { name: 'spinach', ... }]
// } Live demo
Use cases
Grouping records by category
Organize products, messages, or tickets into sections before rendering a grouped interface.
Summaries and rollups
Split scores, statuses, or event types into buckets before counting or aggregating each bucket.
Cautions
- Object.groupBy coerces keys to strings, so use Map.groupBy when key identity or non-string keys matter.
- If grouped arrays become very large, you may still need a second pass for counting, sorting, or filtering.
Accessibility
- When grouped data becomes a UI with sections, give each group a clear heading so users can understand the structure quickly.
Related links
Powered by web-features