Sort dates newest first in date-fns
Lists such as recent posts or activity feeds usually show the newest date first. This example calls compareAsc with the arguments swapped to get that order.
How it works
- Start with native dates. The array holds plain
Dateobjects. No wrapper type is needed. [1] - Swap the arguments. The sort callback is
(a, b) => compareAsc(b, a). Passingbfirst prints the list newest first, while plaincompareAscgives the ascending order shown in the README. [1] - Print both orders. The code prints the ascending and descending lists side by side. Each date is shown with
format(d, "yyyy-MM-dd"). [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(2023, 4, 20),
new Date(2021, 0, 1),
new Date(2024, 9, 15),
new Date(2022, 6, 4),
];
const ascending = [...dates].sort(compareAsc);
// Swap the arguments for newest first
const descending = [...dates].sort((a, b) => compareAsc(b, a));
console.log("Oldest first:", show(ascending));
console.log("Newest first:", show(descending));
Both lines come from the same array, sorted with different callbacks. Code written by AgentGid [1].
Both lines come from the same array, sorted with different callbacks. 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 oldest 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.