Sort objects by a date field in date-fns
Real data is usually a list of records with a date field, not bare dates. This example sorts tasks by their due date.
How it works
- Store dates on objects. Each task has a
nameand aduefield that holds a nativeDate. [1] - Compare the date field. The sort callback
(a, b) => compareAsc(a.due, b.due)passes the twoduedates tocompareAsc. The tasks are printed earliest due date first. [1] - Print each task. Each line shows the formatted due date and the task name.
formatbuilds the yyyy-MM-dd text. [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 tasks = [
{ name: "Write report", due: new Date(2024, 5, 14) },
{ name: "Book flights", due: new Date(2024, 4, 2) },
{ name: "Renew passport", due: new Date(2024, 3, 28) },
{ name: "Team review", due: new Date(2024, 5, 3) },
];
const byDue = [...tasks].sort((a, b) => compareAsc(a.due, b.due));
console.log("Tasks by due date:");
for (const t of byDue) {
console.log(` ${format(t.due, "yyyy-MM-dd")} ${t.name}`);
}
Rename the due field or add tasks to try it with your own data. Code written by AgentGid [1].
Rename the due field or add tasks to try it with your own data. 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
Format a date as yyyy-MM-dd in date-fns Sort dates oldest first 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.