Sorting
The sorting module provides a generic utility to sort arrays by one or more criteria, with support for ascending/descending order, locale-aware string comparison, and null/undefined handling.
Import
import { sortByCriteria, SortOrder } from '@open-kerno/commons/sorting';
SortOrder
An enum describing the sort direction for a criterion.
enum SortOrder {
Asc = 'asc',
Desc = 'desc',
}
sortByCriteria
Sorts an array by one or more criteria, evaluated in order until a criterion yields a difference. Returns a new array; the original is not mutated.
Signature
function sortByCriteria<T>(items: T[], criteria: Array<SortCriterion<T>>): T[]
SortCriterion<T>
| Property | Type | Description |
|---|---|---|
callback | (item: T) => string | number | boolean | Date | null | undefined | Extracts the value to compare for this criterion |
sortOrder | SortOrder (optional) | Direction for this criterion, defaults to SortOrder.Asc |
Parameters
| Parameter | Type | Description |
|---|---|---|
items | T[] | The source array |
criteria | Array<SortCriterion<T>> | Ordered list of criteria; ties fall through to the next one |
Returns
A new, sorted T[]. Strings are compared with localeCompare. Items where a criterion's callback returns null or undefined are always placed at the end, regardless of sort direction.
Example
import { sortByCriteria, SortOrder } from '@open-kerno/commons/sorting';
const orders = [
{ customer: 'b', total: 20 },
{ customer: 'a', total: 20 },
{ customer: 'a', total: 10 },
];
const sorted = sortByCriteria(orders, [
{ callback: (order) => order.customer },
{ callback: (order) => order.total, sortOrder: SortOrder.Desc },
]);
console.log(sorted);
// [
// { customer: 'a', total: 20 },
// { customer: 'a', total: 10 },
// { customer: 'b', total: 20 },
// ]