mirror of
https://github.com/toss/es-toolkit.git
synced 2024-12-01 10:45:08 +03:00
e9ede74362
* Translate Simplified Chinese * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Supplement the omitted * Update docs/.vitepress/shared.mts --------- Co-authored-by: Sojin Park <raon0211@gmail.com>
705 B
705 B
countBy
根据 mapper
函数统计数组中每个项目的出现次数。
签名
function countBy<T>(arr: T[], mapper: (item: T) => string): Record<string, number>
参数
arr
(T[]
): 输入数组,用于统计每个项目的出现次数。mapper
((item: T) => string
): 将每个项目映射到字符串键的转换函数。
返回值
(Record<string, number>
) 包含基于转换函数的每个项目计数的对象。
示例
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);
// 输出: { 'odd': 3, 'even': 3 }