boil
從數組中提取唯一值,類似於去重操作。
語法
typescript
boil<T>(
array: T[],
key?: (item: T) => any
): T[]
參數
array
(T[]): 要處理的數組key
((item: T) => any, 可選): 用於比較的鍵提取函數
返回值
T[]
: 去重後的數組
示例
基本用法
typescript
import { boil } from 'radash'
const numbers = [1, 2, 2, 3, 3, 4, 5, 5]
const uniqueNumbers = boil(numbers)
// [1, 2, 3, 4, 5]
使用對象數組
typescript
import { boil } from 'radash'
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }, // 重復
{ id: 3, name: 'Charlie' }
]
const uniqueUsers = boil(users, user => user.id)
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' },
// { id: 3, name: 'Charlie' }
// ]
使用多個鍵
typescript
import { boil } from 'radash'
const products = [
{ id: 1, name: 'Laptop', category: 'Electronics' },
{ id: 2, name: 'Phone', category: 'Electronics' },
{ id: 1, name: 'Laptop', category: 'Electronics' }, // 重復
{ id: 3, name: 'Book', category: 'Education' }
]
const uniqueProducts = boil(products, product => `${product.id}-${product.category}`)
// [
// { id: 1, name: 'Laptop', category: 'Electronics' },
// { id: 2, name: 'Phone', category: 'Electronics' },
// { id: 3, name: 'Book', category: 'Education' }
// ]
處理字符串數組
typescript
import { boil } from 'radash'
const tags = ['javascript', 'typescript', 'javascript', 'react', 'typescript']
const uniqueTags = boil(tags)
// ['javascript', 'typescript', 'react']
處理嵌套對象
typescript
import { boil } from 'radash'
const orders = [
{ id: 1, customer: { id: 101, name: 'Alice' } },
{ id: 2, customer: { id: 102, name: 'Bob' } },
{ id: 3, customer: { id: 101, name: 'Alice' } } // 重復客戶
]
const uniqueByCustomer = boil(orders, order => order.customer.id)
// [
// { id: 1, customer: { id: 101, name: 'Alice' } },
// { id: 2, customer: { id: 102, name: 'Bob' } }
// ]
處理日期對象
typescript
import { boil } from 'radash'
const events = [
{ id: 1, date: new Date('2023-01-01'), title: 'Event 1' },
{ id: 2, date: new Date('2023-01-02'), title: 'Event 2' },
{ id: 3, date: new Date('2023-01-01'), title: 'Event 3' } // 重復日期
]
const uniqueByDate = boil(events, event => event.date.toISOString().split('T')[0])
// [
// { id: 1, date: new Date('2023-01-01'), title: 'Event 1' },
// { id: 2, date: new Date('2023-01-02'), title: 'Event 2' }
// ]
注意事項
- 保留順序: 保留第一次出現的元素
- 鍵函數: 如果不提供鍵函數,直接比較元素值
- 對象比較: 對於對象,需要提供鍵函數進行有效去重
- 性能: 時間復雜度為 O(n²),適用於中小型數組
與其他函數的區別
boil
: 去重操作,保留第一次出現的元素unique
: 類似功能,但可能有不同的實現distinct
: 其他庫的類似功能
性能
- 時間復雜度: O(n²)
- 空間復雜度: O(n)
- 適用場景: 中小型數組的去重操作