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
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
items | readonly T[] | null | undefined | The array to group |
keyFn | function | Function that returns the group key for each item |
Returns
Section titled “Returns”Partial<Record<K, T[]>> — A record mapping each key to the array of items with that key
Examples
Section titled “Examples”Group numbers by parity
Section titled “Group numbers by parity”Groups elements by the string key returned by the callback.
Group objects by a property
Section titled “Group objects by a property”Use a property accessor as the grouping key.
