Sort dates oldest first in date-fns
compareAsc is a compare function you can hand to Array.prototype.sort to put dates in ascending order. This example sorts three dates and prints them before and after.
How it works
- Create the dates. The array holds three native
Datevalues in random order. The code prints them first so you can compare. [1] - Sort with compareAsc.
[...dates].sort(compareAsc)sorts a copy of the array usingcompareAscas the compare function. The result is printed oldest first. [1] - Print readable dates. A small helper uses
formatwith"yyyy-MM-dd"so each line is easy to read. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { compareAsc, format } from "date-fns";
const show = (list) => list.map((d) => format(d, "yyyy-MM-dd")).join(", ");
const dates = [
new Date(1995, 6, 2),
new Date(1987, 1, 11),
new Date(1989, 6, 10),
];
console.log("Before:", show(dates));
const sorted = [...dates].sort(compareAsc);
console.log("Oldest first:", show(sorted));
Add more dates to the array and the sorted list updates on the next run. Code written by AgentGid [1].
Add more dates to the array and the sorted list updates on the next run. Code written by AgentGid [1].Checked Oct 14, 2026: it starts without errors in Chromium with date-fns 4.4.0. Needs WebGL.
More date-fns examples
Sort objects by a date field in date-fns Format a date as yyyy-MM-dd in date-fns Sort dates newest first in date-fns Group dates by day in date-fns
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.