For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/fp/countBy.md.

countBy (Functional Programming) es-toolkit

Creates a function that counts values by a key. Use it with pipe.

const result = pipe(array, countBy(mapper));
Info

Prefer the original es-toolkit countBy in ordinary code. Use this fp variant when composing transformations with pipe.

Usage

countBy calls mapper for each value in the piped array and returns an object whose keys are mapper results and whose values are counts.

import { countBy, pipe } from 'es-toolkit/fp';

pipe(
  ['one', 'two', 'three'],
  countBy(word => word.length)
); // => { 3: 2, 5: 1 }

Parameters

mapper(item: T) => Krequired

The function that returns the key used for counting.

Returns

A function that maps a readonly T[] to counts by key.

(array: readonly T[]) => Record<K, number>
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.