es-toolkit/docs/reference/array/countBy.md
HyunWoo Lee (Nunu Lee) 373d63b980
feat(countBy): Add countBy function (#117)
* [feature/#88] Add countBy.ts

* [feature/#88] Add benchmark test of countBy

* [feature/#88] Add test code

* [feature/#88] Add countBy references

* Update docs/ko/reference/array/countBy.md

* Apply suggestions from code review

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
2024-07-03 10:09:12 +09:00

735 B

countBy

Count the occurrences of each item in an array based on a mapper function.

Signature

function countBy<T>(arr: T[], mapper: (item: T) => string): Record<string, number>

Parameters

  • arr (T[]): The input array to count occurrences.
  • mapper ((item: T) => string): The transformation function that maps each item to a string key.

Returns

(Record<string, number>) An object containing the count of each item based on the transformation function.

Examples

import { countBy } from 'es-toolkit/array';

const array = [1, 2, 3, 4, 5, 6];
const result = countBy(array, x => x % 2 === 0 ? 'even' : 'odd');

console.log(result);
// Output: { 'odd': 3, 'even': 3 }