countBy
countBy() function
Returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, it returns a count for the number of values in that group.
Signature:declare function countBy<A, B extends Key>(f: (a: A) => B, iterable: Iterable<A>): {
[K in B]: number;
};
declare function countBy<A, B extends Key>(f: (a: A) => B | Promise<B>, iterable: AsyncIterable<A>): Promise<{
[K in B]: number;
}>;
declare function countBy<A extends Iterable<unknown> | AsyncIterable<unknown>, B extends Key>(f: (a: IterableInfer<A>) => B | Promise<B>): (iterable: A) => ReturnValueType<A, {
[K in B]: number;
}>;
Example
const given = [
{ category: "clothes", desc: "good" },
{ category: "pants", desc: "bad" },
{ category: "shoes", desc: "not bad" },
{ category: "shoes", desc: "great" },
{ category: "pants", desc: "good" },
];
countBy((a) => a.category, given);
//{
// clothes: 1,
// pants: 2,
// shoes: 2,
// };