Object.groupBy()
Groups elements of an iterable into an object keyed by the result of a callback.
Syntax
Object.groupBy(items, callbackFn) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
items | object | Yes | An iterable (such as an array) whose elements will be grouped. |
callbackFn | Function | Yes | Function called with (element, index). Returns a string or symbol used as the group key. |
Returns
object — A null-prototype object whose keys are group names and values are arrays of elements.
Examples
const nums = [1, 2, 3, 4, 5];
const g = Object.groupBy(nums, n => (n % 2 === 0 ? 'even' : 'odd'));
console.log(g);
Output
[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }
const data = [{ t: 'a' }, { t: 'b' }, { t: 'a' }];
console.log(Object.groupBy(data, x => x.t));
Output
[Object: null prototype] { a: [ { t: 'a' }, { t: 'a' } ], b: [ { t: 'b' } ] }
Notes
Returns a null-prototype object (no inherited keys, safe as a lookup table).
Use `Map.groupBy` when keys are objects or non-string values. Replaces the
unshipped `Array.prototype.group` proposal.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 117 |
| firefox | 119 |
| safari | 17.4 |
| edge | 117 |
| node | 21 |