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 是唯一元素的數量
- 適用場景: 數據分析和統計