Skip to content

createSortByNumberFn

Creates a sort function for objects by number property.

Available since v1.9.0

import { createSortByNumberFn } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { createSortByNumberFn } from 'helpers4/array';
createSortByNumberFn<T extends Record<string, unknown>>(property?: keyof T): SortFn<T>
ParameterTypeDescription
propertykeyof TThe property to sort by (defaults to `‘value’`). Always pass an explicit key when T does not have a `‘value’` property — omitting it on such types produces a no-op comparator (all elements compare equal). `null` and `undefined` sort last (treated as `+Infinity`). Non-numeric values (including booleans — `Number(true) === 1`, `Number(false) === 0`) and `NaN` also sort last. (optional)

SortFn<T> — Sort function

const items = [{ count: 3 }, { count: 1 }, { count: 2 }];
items.sort(createSortByNumberFn('count'))
// => [{ count: 1 }, { count: 2 }, { count: 3 }]

Sort function type for arrays

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

View source on GitHub