countBy
Groups the elements of an array by the key returned by keyFn and returns a
record mapping each key to the number of matching elements.
null and undefined are treated as empty arrays and return {}.
Items whose computed key is a prototype-polluting string (__proto__,
constructor, prototype) are silently skipped.
Available since v2.0.0
Import
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
array | readonly T[] | null | undefined | The array to count. |
keyFn | function | A function that returns the grouping key for each element. |
Returns
Section titled “Returns”Partial<Record<Exclude<K, UnsafeKey>, number>> — A Partial<Record<K, number>> where each key maps to its element count.
Prototype-polluting keys (__proto__, constructor, prototype) are never present.
Examples
Section titled “Examples”Count by parity
Section titled “Count by parity”Groups items by the string key returned by the callback and counts occurrences.
Count commit types
Section titled “Count commit types”Use any string transform as the grouping key.
