Skip to main content

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>

PropertyTypeDescription
callback(item: T) => string | number | boolean | Date | null | undefinedExtracts the value to compare for this criterion
sortOrderSortOrder (optional)Direction for this criterion, defaults to SortOrder.Asc

Parameters

ParameterTypeDescription
itemsT[]The source array
criteriaArray<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 },
// ]