Skip to content

groupBy

Groups an array of items by a key derived from each item.

A thin, typed wrapper around Object.groupBy (ES2024) that works on older targets and provides stricter return-type inference. null and undefined are treated as empty arrays and return {}. Items whose computed key is a prototype-polluting string (__proto__, constructor, prototype) are silently skipped.

Available since v2.0.0

import { groupBy } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { groupBy } from 'helpers4/object';
groupBy<T, K extends PropertyKey>(items: readonly T[] | null | undefined, keyFn: function): Partial<Record<K, T[]>>
ParameterTypeDescription
itemsreadonly T[] | null | undefinedThe array to group
keyFnfunctionFunction that returns the group key for each item

Partial<Record<K, T[]>> — A record mapping each key to the array of items with that key

Groups elements by the string key returned by the callback.

groupBy([1, 2, 3, 4], n => n % 2 === 0 ? 'even' : 'odd')
// => { odd: [1, 3], even: [2, 4] }

Use a property accessor as the grouping key.

const users = [
  { name: 'Alice', role: 'admin' },
  { name: 'Bob',   role: 'user'  },
  { name: 'Carol', role: 'admin' },
];
groupBy(users, u => u.role)
// => { admin: [{...Alice}, {...Carol}], user: [{...Bob}] }

View source on GitHub