JavaScript Reference ยท Object
Object.groupBy()
Reference for JavaScript Object.groupBy(): group items of an iterable by a key function into an object of arrays, and how it compares with Map.groupBy().
Object.groupBy() sorts the items of an iterable into groups. You supply a callback that returns a key for each item, and the result is an object whose property names are those keys and whose values are arrays of the matching items.
It replaces the common reduce() pattern for grouping. The returned object has a null prototype, so keys like toString cannot clash with inherited members.
Object.groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even")); // { odd: [1, 3], even: [2, 4] }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.groupBy(items, callbackFn)
| Name | Description |
|---|---|
items |
An iterable, such as an array, a string or a Set. |
callbackFn |
Called once per item with (item, index). It returns the group key, which is converted to a property key (a string or symbol). |
Return value: a null-prototype object. Each property is an array of the items in that group, in their original order.
Exceptions: a TypeError if items is not iterable or callbackFn is not a function. Errors thrown by the callback propagate.
Usage notes
- Keys become strings (or symbols). If you group by numbers, the keys are strings such as
"1". When you need other key types, such as objects, useMap.groupBy(), which keeps keys as they are. - Items are not copied. The arrays hold the same references as the source.
- Group order: keys follow the usual object order, with integer-like keys first in ascending order, then others in the order they first appeared.
- Empty result is fine. An empty iterable gives an object with no properties.
- Null prototype: the result has no
hasOwnPropertyortoString, so test for a group withObject.hasOwn(result, key)orkey in result. Convert with{ ...result }if you need an ordinary object. - It does not sort or deduplicate. It only partitions.
- The index is the second callback argument, which allows grouping by position.
Browser support
Object.groupBy() and Map.groupBy() are recent additions. They work in current browsers and runtimes, but older versions lack them, so check a compatibility table before relying on them in code that must run on older browsers.