Skip to content

dependabit / utils/src / groupBy

Function: groupBy()

ts
function groupBy<T, K>(arr, keyFn): Record<K, T[]>;

Defined in: packages/utils/src/array.ts:31

Groups array elements by a key function.

Type Parameters

Type Parameter
T
K extends string | number

Parameters

ParameterTypeDescription
arrT[]The array to group.
keyFn(item) => KFunction that maps each element to a group key.

Returns

Record<K, T[]>

An object with grouped elements.

Example

ts
groupBy([1, 2, 3], n => n % 2); // { '0': [2], '1': [1, 3] }

Released under the MIT License.