alphabetical
Sort an array alphabetically.
Syntax
typescript
alphabetical<T>(
array: T[],
key?: (item: T) => string
): T[]
Parameters
array
(T[]): The array to sortkey
((item: T) => string, optional): Key extraction function for sorting
Return Value
T[]
: Array sorted alphabetically
Examples
Basic Usage
typescript
import { alphabetical } from 'radash'
const fruits = ['banana', 'apple', 'cherry', 'date']
const sorted = alphabetical(fruits)
// ['apple', 'banana', 'cherry', 'date']
Using Object Arrays
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 }
// ]
Using Nested Properties
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' } }
// ]
Handling Null and Undefined Values
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' }
// ]
Notes
- Default Behavior: If no
key
function is provided, the array elements will be sorted directly as strings - Case Sensitivity: Sorting is case-sensitive, uppercase letters will be sorted before lowercase letters
- Null Value Handling: Null values, null, and undefined will be converted to empty strings for sorting
- Stability: The sort is stable, the relative positions of identical values will not change
Differences from Other Functions
alphabetical
is specifically designed for alphabetical sortingsort
(native) requires custom comparison functionsorderBy
(Lodash) has more complex functionality, supporting multi-field sorting
Performance
Time Complexity: O(n log n)
Space Complexity: O(n)
Suitable for sorting requirements of small to medium-sized arrays.