Skip to content

createSortByDateFn

Creates a sort function for objects by date property.

Available since v1.9.0

import { createSortByDateFn } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { createSortByDateFn } from 'helpers4/array';
createSortByDateFn<T extends Record<string, unknown>>(property?: keyof T): SortFn<T>
ParameterTypeDescription
propertykeyof TThe property to sort by (defaults to `‘date’`). Accepted value types: `Date` (including cross-realm instances), `string`, or `number` (Unix milliseconds). Any object with a `getTime(): number` method is also accepted (duck-typed, so cross-realm `Date` objects work correctly). `null`, `undefined`, and unparseable strings produce `NaN` and sort last, distinct from a genuine Unix-epoch date (`new Date(0)`). (optional)

SortFn<T> — Sort function

const events = [
  { date: new Date('2023-01-01') },
  { date: new Date('2021-06-15') },
];
events.sort(createSortByDateFn('date'))
// => sorted oldest first

Sort function type for arrays

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

View source on GitHub