Skip to content

countBy

Groups the entries of a Map by a derived key and counts how many fall into each group.

Available since v3.0.3

import { countBy } from '@helpers4/map';
// or, from the all-in-one package (same code, one install):
import { countBy } from 'helpers4/map';
countBy<K, V, R>(map: ReadonlyMap<K, V>, fn: function): Map<R, number>
ParameterTypeDescription
mapReadonlyMap<K, V>The Map to summarize
fnfunctionFunction deriving the grouping key from (value, key)

Map<R, number> — A Map from derived key to the number of entries in that group

Groups values by a derived key and counts how many fall into each group.

countBy(new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4]]), v => v % 2 === 0 ? 'even' : 'odd')
// => Map(2) { 'odd' => 2, 'even' => 2 }

View source on GitHub