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)
- 适用场景: 中小型数组的去重操作