sort
The sort utility provides a simple, functional way to sort arrays. Unlike the native Array.prototype.sort(), it returns a new array and allows sorting based on a selector function with an optional descending flag.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { compare } from '../function/compare';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
/**
* Sorts an array of objects by a specific key in ascending order.
*
* @example
* ```ts
* const data = [{ a: 2 }, { a: 3 }, { a: 1 }];
* sort(data, (item) => item.a); // [{ a: 1 }, { a: 2 }, { a: 3 }]
* ```
*
* @param array - The array of objects to sort.
* @param selector - A function that extracts the key to sort by.
* @param desc - A boolean indicating whether to sort in descending order (default: false).
*
* @returns A new array sorted by the specified key.
*
* @throws {TypeError} If the provided array is not an array.
*/
// biome-ignore lint/suspicious/noExplicitAny: -
export const sort = <T>(array: T[], selector: (item: T) => any, desc = false) => {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
const multiplier = desc ? -1 : 1;
return [...array].sort((a, b) => compare(selector(a), selector(b)) * multiplier);
};
sort.fp = true;Features
- Isomorphic: Works in both Browser and Node.js.
- Immutable: Returns a new sorted array, leaving the original untouched.
- Selector Support: Sort by any property or computed value.
- Custom Order: Easily toggle between ascending and descending order.
API
ts
function sort<T>(array: T[], selector: (item: T) => any, desc?: boolean): T[];Parameters
array: The array to sort.selector: A function that extracts the value to compare from each element.desc: Optional. Iftrue, the array is sorted in descending order (defaults tofalse).
Returns
- A new sorted array.
Examples
Sorting Numbers
ts
import { sort } from '@vielzeug/toolkit';
const numbers = [10, 2, 33, 4, 1];
// Ascending (default)
sort(numbers, (n) => n); // [1, 2, 4, 10, 33]
// Descending
sort(numbers, (n) => n, true); // [33, 10, 4, 2, 1]Sorting Objects
ts
import { sort } from '@vielzeug/toolkit';
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 20 },
{ name: 'Charlie', age: 30 },
];
// Sort by age
const byAge = sort(users, (u) => u.age);
// [{ name: 'Bob', ... }, { name: 'Alice', ... }, { name: 'Charlie', ... }]Implementation Notes
- Throws
TypeErrorif the first argument is not an array. - Uses a stable sorting algorithm (where supported by the environment).
- Internally uses a generic
comparehelper to handle different data types consistently.