iteration
Object.groupBy
Groups the elements of an iterable into an object keyed by the string returned from the callback. Introduced in ES2024 (Node 21+, modern browsers 2024+).
Object.groupBy(items, callback) Parameters
| Parameter | Purpose |
|---|---|
| items | The iterable to group |
| callback | Function (item, index) => key returning the group key (coerced to a property key) |
| returns | A null-prototype object whose values are arrays of grouped items |
Examples
const nums = [1, 2, 3, 4, 5];
console.log(Object.groupBy(nums, n => n % 2 ? 'odd' : 'even')); Logs { odd: [1, 3, 5], even: [2, 4] }
const people = [{ name: 'Ada', role: 'eng' }, { name: 'Bo', role: 'pm' }, { name: 'Cy', role: 'eng' }];
console.log(Object.groupBy(people, p => p.role)); Logs { eng: [{...Ada}, {...Cy}], pm: [{...Bo}] }
console.log(Object.getPrototypeOf(g)); Logs `null` — Object.groupBy returns an object with a null prototype.
console.log(Object.groupBy(['apple', 'apricot', 'banana'], s => s[0])); Logs { a: ['apple', 'apricot'], b: ['banana'] }
Gotcha
ES2024 — requires Node 21+, Chrome 117+, Safari 17.4+, Firefox 119+. The returned object has a NULL prototype (safe for arbitrary keys). For grouping into a Map instead, use Map.groupBy.
Related methods
Object.fromEntries
Transforms a list of key-value pairs into an object — the inverse of Object.entries. Introduced in ES2019 and accepts any iterable of [key, value] pairs, including Map.
Object.entries
Returns an array of a given object's own enumerable string-keyed [key, value] pairs. Useful for iterating objects with for...of destructuring or converting to a Map.
Object.keys
Returns an array of a given object's own enumerable string-keyed property names. The order matches a normal for...in loop but excludes inherited and non-enumerable properties.