counting
统计数组中每个元素出现的次数。
语法
typescript
counting<T>(
array: T[],
key?: (item: T) => any
): Record<string, number>
参数
array
(T[]): 要统计的数组key
((item: T) => any, 可选): 用于统计的键提取函数
返回值
Record<string, number>
: 统计结果对象,键为元素值,值为出现次数
示例
基本用法
typescript
import { counting } from 'radash'
const fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
const counts = counting(fruits)
// { 'apple': 3, 'banana': 2, 'cherry': 1 }
统计对象数组
typescript
import { counting } from 'radash'
const users = [
{ name: 'Alice', city: 'New York' },
{ name: 'Bob', city: 'Los Angeles' },
{ name: 'Charlie', city: 'New York' },
{ name: 'Diana', city: 'Los Angeles' },
{ name: 'Eve', city: 'New York' }
]
const cityCounts = counting(users, user => user.city)
// { 'New York': 3, 'Los Angeles': 2 }
统计数字数组
typescript
import { counting } from 'radash'
const scores = [85, 92, 78, 85, 90, 92, 85]
const scoreCounts = counting(scores)
// { '85': 3, '92': 2, '78': 1, '90': 1 }
统计嵌套属性
typescript
import { counting } from 'radash'
const orders = [
{ id: 1, customer: { name: 'Alice', tier: 'Gold' } },
{ id: 2, customer: { name: 'Bob', tier: 'Silver' } },
{ id: 3, customer: { name: 'Charlie', tier: 'Gold' } },
{ id: 4, customer: { name: 'Diana', tier: 'Bronze' } }
]
const tierCounts = counting(orders, order => order.customer.tier)
// { 'Gold': 2, 'Silver': 1, 'Bronze': 1 }
统计条件结果
typescript
import { counting } from 'radash'
const products = [
{ name: 'Laptop', price: 999 },
{ name: 'Phone', price: 599 },
{ name: 'Book', price: 29 },
{ name: 'Tablet', price: 399 },
{ name: 'Watch', price: 199 }
]
const priceRangeCounts = counting(products, product => {
if (product.price < 100) return 'Budget'
if (product.price < 500) return 'Mid-range'
return 'Premium'
})
// { 'Budget': 1, 'Mid-range': 2, 'Premium': 2 }
统计布尔值
typescript
import { counting } from 'radash'
const responses = [true, false, true, true, false, true]
const responseCounts = counting(responses)
// { 'true': 4, 'false': 2 }
处理空值
typescript
import { counting } from 'radash'
const items = [
{ name: 'Item 1', category: 'A' },
{ name: 'Item 2', category: null },
{ name: 'Item 3', category: 'B' },
{ name: 'Item 4', category: undefined },
{ name: 'Item 5', category: 'A' }
]
const categoryCounts = counting(items, item => item.category || 'Uncategorized')
// { 'A': 2, 'B': 1, 'Uncategorized': 2 }
统计字符串字符
typescript
import { counting } from 'radash'
const text = 'hello world'
const charCounts = counting(text.split(''))
// { 'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1 }
注意事项
- 键转换: 所有键都会被转换为字符串
- 空值处理: 需要手动处理 null 和 undefined 值
- 性能: 时间复杂度为 O(n)
- 大小写: 字符串区分大小写
与其他函数的区别
counting
: 统计元素出现次数countBy
: 类似功能,但可能有不同的实现frequency
: 其他库的类似功能
性能
- 时间复杂度: O(n)
- 空间复杂度: O(k),其中 k 是唯一元素的数量
- 适用场景: 数据分析和统计