Skip to content

Function: sortArray() ​

sortArray<T>(array, ...options): T[]

Sort an array in place and return it (the same array, modified). The values are compared with < and >: the numbers numerically, the strings by UTF-16 code units (upper case before lower case: 'C' before 'a'; use localeCompare with Array.prototype.sort for a human order). The null, NaN and undefined keys go after the other values, in both orders, unless nullRank or undefinedRank puts them before.

Without options, the items themselves are sorted ascending. With one set of options, by its by properties in its order, with its computed keys, customOrders, nullRank and undefinedRank. With several sets, each one names one property (by) and its order, the first set deciding first: an option set without by is skipped.

Type Parameters ​

T ​

T = any

Parameters ​

array ​

T[]

The array to sort; an empty array is returned as is.

options ​

...SortArrayOptions<T>[]

The sort keys and orders: none, one set, or one set per property (see SortArrayOptions).

Returns ​

T[]

The array itself, sorted.

Throws ​

When sorting by a property of an item which is null or undefined (not an object).

Example ​

typescript
import {sortArray} from 'lakutata/utils'

type Person = {name: string, age: number}

const people: Person[] = [{name: 'Bob', age: 30}, {name: 'Ada', age: 30}, {name: 'Cy', age: 20}]
//The oldest first, by name among the same age
sortArray(people, {by: ['age', 'name'], order: ['desc', 'asc']})
console.log(people.map((person: Person): string => person.name))
//['Ada', 'Bob', 'Cy']
//A computed key: the length of the name
sortArray(people, {by: 'length', computed: {length: (person: Person): number => person.name.length}})
console.log(people.map((person: Person): string => person.name))
//['Cy', 'Ada', 'Bob']
console.log(sortArray([3, null, 1, 2]))
//[1, 2, 3, null]

Released under the MIT License.