Skip to content

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:

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

Example

ts
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,
// };

Try It

Open Source Code

Released under the Apache-2.0 License.