Array grouping
Note: In some versions of some browsers, this method was implemented as the method Array.prototype.groupToMap(). Due to web compatibility issues, it is now implemented as a static method. Check the browser compatibility table for details.
The Map.groupBy() static method groups the elements of a given iterable using the values returned by a provided callback function. The final returned Map uses the unique values from the test function as keys, which can be used to get the array of elements in each group.
The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with Object.groupBy().
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.