Skip to content

reverseSortFn

Reverses the order of a sort function: reverseSortFn(fn)(a, b) is fn(b, a).

Gives a descending variant of any comparator, including the ones built by the createSortBy*Fn factories, and composes with combineSortFns for mixed orders. Ties stay ties, so the sort remains stable.

Available since v3.1.4

import { reverseSortFn } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { reverseSortFn } from 'helpers4/array';
reverseSortFn<T>(fn: SortFn<T>): SortFn<T>
ParameterTypeDescription
fnSortFn<T>The sort function to reverse

SortFn<T> — A sort function with the opposite order

Turns an ascending comparator into a descending one.

const releases = [{ date: '2026-01-01' }, { date: '2026-03-01' }];
releases.sort(reverseSortFn(createSortByStringFn('date')))
// => [{ date: '2026-03-01' }, { date: '2026-01-01' }]

Newest first, then name ascending, by combining it with combineSortFns.

rows.sort(combineSortFns(
  reverseSortFn(createSortByStringFn('date')),
  createSortByStringFn('name'),
))

Sort function type for arrays

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

View source on GitHub