R
fn

groupBy

v0.0.10tested

Groups the elements of an array by the key returned by `getKey`

Examples

ts
groupBy([1, 2, 3, 4], n => (n % 2 === 0 ? 'even' : 'odd'))
// => { odd: [1, 3], even: [2, 4] }
ts
groupBy([{ type: 'a', v: 1 }, { type: 'b', v: 2 }, { type: 'a', v: 3 }], item => item.type)
// => { a: [{ type: 'a', v: 1 }, { type: 'a', v: 3 }], b: [{ type: 'b', v: 2 }] }

Signature

ts
export function groupBy<Value, Key extends PropertyKey>(
  array: Value[],
  getKey: (item: Value, index: number) => Key,
): Record<Key, Value[]>{ ... }

Type Parameters

Value
Keyextends PropertyKey

Parameters

ParameterTypeDescription
arrayValue[]The array to group
getKey(item: Value, index: number) => KeyMaps an element to its group key

Returns

Record<Key, Value[]>An object of arrays, keyed by group