Skip to content

alphabetical

按字母顺序对数组进行排序。

语法

typescript
alphabetical<T>(
  array: T[],
  key?: (item: T) => string
): T[]

参数

  • array (T[]): 要排序的数组
  • key ((item: T) => string, 可选): 用于排序的键提取函数

返回值

  • T[]: 按字母顺序排序后的数组

示例

基本用法

typescript
import { alphabetical } from 'radash'

const fruits = ['banana', 'apple', 'cherry', 'date']
const sorted = alphabetical(fruits)
// ['apple', 'banana', 'cherry', 'date']

使用对象数组

typescript
import { alphabetical } from 'radash'

const users = [
  { name: 'Charlie', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
]

const sortedByName = alphabetical(users, user => user.name)
// [
//   { name: 'Alice', age: 25 },
//   { name: 'Bob', age: 35 },
//   { name: 'Charlie', age: 30 }
// ]

使用嵌套属性

typescript
import { alphabetical } from 'radash'

const products = [
  { name: 'Laptop', category: { name: 'Electronics' } },
  { name: 'Book', category: { name: 'Education' } },
  { name: 'Phone', category: { name: 'Electronics' } }
]

const sortedByCategory = alphabetical(products, product => product.category.name)
// [
//   { name: 'Book', category: { name: 'Education' } },
//   { name: 'Laptop', category: { name: 'Electronics' } },
//   { name: 'Phone', category: { name: 'Electronics' } }
// ]

处理空值和undefined

typescript
import { alphabetical } from 'radash'

const items = [
  { name: 'Item 1', description: 'First item' },
  { name: null, description: 'Null name' },
  { name: 'Item 2', description: 'Second item' },
  { name: undefined, description: 'Undefined name' }
]

const sorted = alphabetical(items, item => item.name || '')
// [
//   { name: null, description: 'Null name' },
//   { name: undefined, description: 'Undefined name' },
//   { name: 'Item 1', description: 'First item' },
//   { name: 'Item 2', description: 'Second item' }
// ]

注意事项

  1. 默认行为: 如果不提供 key 函数,将直接对数组元素进行字符串排序
  2. 大小写敏感: 排序是大小写敏感的,大写字母会排在小写字母之前
  3. 空值处理: 空值、null 和 undefined 会被转换为空字符串进行排序
  4. 稳定性: 排序是稳定的,相同值的相对位置不会改变

与其他函数的区别

  • alphabetical 专门用于字母排序
  • sort (原生) 需要自定义比较函数
  • orderBy (Lodash) 功能更复杂,支持多字段排序

性能

时间复杂度: O(n log n)
空间复杂度: O(n)

适用于中小型数组的排序需求。

Released under the MIT License.