countBy

collection

Creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.

Signature

countBy<T>(collection: T[], iteratee: ((value: T) => PropertyKey) | keyof T): Record<PropertyKey, number>

Parameters

NameTypeDescription
collectionT[]The collection to iterate over
iteratee((value: T) => PropertyKey) | keyof TThe iteratee to transform keys

Returns

Record<PropertyKey, number> - Returns the composed aggregate object

Examples

Count by function result

import { countBy } from 'dashlite'

const result = countBy([6.1, 4.2, 6.3], Math.floor)
console.log(result)

Output:

{ '4': 1, '6': 2 }

Count by property

import { countBy } from 'dashlite'

const users = [
  { role: 'admin' },
  { role: 'user' },
  { role: 'admin' }
]
const result = countBy(users, 'role')
console.log(result)

Output:

{ admin: 2, user: 1 }

Available since version 1.2.0