Object.groupBy
Groups the elements of an array by a key.
Available since: ES2024
Syntax
Object.groupBy(items, callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| items | Iterable | An array or another iterable. |
| callbackFn | Function | A function that returns the group key for an element. |
Return value
objectAn object where each key is a group and the value is an array of its elements.
Examples
Even and odd numbers:
const groups = Object.groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? 'even' : 'odd'));
console.log(groups.even.join(', '));
console.log(groups.odd.join(', '));Output:
2, 4
1, 3, 5Products by category:
const products = [
{ name: 'Apple', type: 'fruit' },
{ name: 'Carrot', type: 'vegetable' },
{ name: 'Pear', type: 'fruit' },
];
const byType = Object.groupBy(products, (product) => product.type);
console.log(byType.fruit.map((p) => p.name).join(', '));
console.log(Object.keys(byType));Output:
Apple, Pear
[
"fruit",
"vegetable"
]Notes
If the group keys are not strings (objects, for example), use Map.groupBy(). Before this method existed grouping was written with reduce().
See also
- Map.groupBy — Groups elements into a Map by any key.
- Array.prototype.reduce — Reduces an array to a single value.
- Array.prototype.filter — Creates a new array from the elements that pass a test.
Related recipes
In the tutorial
- Iterating objects and Object functions — How to iterate over an object in JavaScript: Object.keys, Object.values, Object.entries, Object.fromEntries, for...in and Object.hasOwn.