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.