Skip to content

combineSortFns

Chains multiple sort functions into a single comparator: the first function decides the order unless it reports a tie (0), in which case the next function is tried, and so on.

Lets you compose comparators of different kinds — e.g. a boolean-property comparator from createSortByBooleanFn followed by a string-property comparator from createSortByStringFn — which a single multi-key call cannot express, since that coerces every key to the same comparison type.

Available since v3.0.0

import { combineSortFns } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { combineSortFns } from 'helpers4/array';
combineSortFns<T>(fns: readonly SortFn<T>[]): SortFn<T>
ParameterTypeDescription
fnsreadonly SortFn<T>[]Sort functions to try, in priority order. An empty list produces a stable no-op comparator (all elements compare equal).

SortFn<T> — A single sort function equivalent to applying fns in order

Chain a boolean comparator with a string comparator to break ties.

const items = [
  { isDefault: false, label: 'Bob' },
  { isDefault: true, label: 'Zoe' },
  { isDefault: false, label: 'Alice' },
];
items.sort(combineSortFns(
  createSortByBooleanFn('isDefault'),
  createSortByStringFn('label'),
))
// => [Zoe (default), Alice, Bob]

Falls through when the first comparator ties

Section titled “Falls through when the first comparator ties”

A 0 result from the first function moves on to the next one.

const rows = [{ a: 1, b: 2 }, { a: 1, b: 1 }];
rows.sort(combineSortFns<{ a: number; b: number }>(
  (x, y) => x.a - y.a,
  (x, y) => x.b - y.b,
))
// => [{ a: 1, b: 1 }, { a: 1, b: 2 }]

Sort function type for arrays

type SortFn<T> = (a: T, b: T) => number

View source on GitHub