Skip to content

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 { countBy } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { countBy } from 'helpers4/array';
countBy<T, K extends PropertyKey>(array: readonly T[] | null | undefined, keyFn: function): Partial<Record<Exclude<K, UnsafeKey>, number>>
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to count.
keyFnfunctionA function that returns the grouping key for each element.

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.

Groups items by the string key returned by the callback and counts occurrences.

countBy([1, 2, 3, 4, 5], n => n % 2 === 0 ? 'even' : 'odd')
// => { odd: 3, even: 2 }

Use any string transform as the grouping key.

const commits = ['feat: add x', 'fix: bug', 'feat: add y'];
countBy(commits, msg => msg.split(':')[0])
// => { feat: 2, fix: 1 }

View source on GitHub