Skip to content

collectBy

The collectBy function groups elements of an array into subarrays based on a key selector function.

Syntax

typescript
collectBy<T, K extends PropertyKey>(
  array: T[],
  keySelector: (value: T, index: number) => K
): T[][];

Parameters

NameTypeDescription
arrayT[]Source array
keySelector(value: T, index: number) => KFunction to select the grouping key

Returns

TypeDescription
T[][]Subarrays grouped by key

Examples

typescript
collectBy([1, 2, 3, 4], x => x % 2); // => [[2,4],[1,3]]
collectBy(["a", "b", "aa"], x => x.length); // => [["a","b"],["aa"]]

Notes

  • Useful for grouping elements by custom criteria.

References

Released under the MIT License.