Skip to main content

groupBy

groupBy() function

Splits Iterable/AsyncIterable into sets, grouped by the result of running each value through f.

Signature:
declare function groupBy<A, B extends Key>(f: (a: A) => B, iterable: Iterable<A>): {
[K in B]: A[];
};

declare function groupBy<A, B extends Key>(f: (a: A) => B | Promise<B>, iterable: AsyncIterable<A>): Promise<{
[K in B]: A[];
}>;

declare function groupBy<A extends Iterable<unknown> | AsyncIterable<unknown>, B extends Key>(f: (a: IterableInfer<A>) => B | Promise<B>): (iterable: A) => ReturnValueType<A, {
[K in B]: IterableInfer<A>[];
}>;

Example

const given = [
{ category: "clothes", desc: "good" },
{ category: "pants", desc: "bad" },
{ category: "shoes", desc: "not bad" },
{ category: "shoes", desc: "great" },
{ category: "pants", desc: "good" },
];

groupBy((a) => a.category, given);
// {
// clothes: [{ category: "clothes", desc: "good" }],
// pants: [
// { category: "pants", desc: "bad" },
// { category: "pants", desc: "good" },
// ],
// shoes: [
// { category: "shoes", desc: "not bad" },
// { category: "shoes", desc: "great" },
// ],
// };

Try It