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

← All JS Object methods · Array methods · Spread vs rest