Sort dates in an array
Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.
A list of Date objects needs a comparator. Subtracting two dates coerces both to their millisecond timestamps, so a - b is negative, zero or positive exactly as a sort callback wants.
const dates = [
new Date('2026-03-01'),
new Date('2025-12-25'),
new Date('2026-01-15'),
];
dates.sort((a, b) => a - b);
console.log(dates.map((d) => d.toISOString().slice(0, 10)));
const text = [new Date('2026-03-01'), new Date('2025-12-25')];
console.log(text.sort().map((d) => d.toDateString()));[ '2025-12-25', '2026-01-15', '2026-03-01' ]
[ 'Mon Mar 02 2026', 'Fri Dec 26 2025' ]The second line is the trap. Without a comparator, sort() converts each item to a string and compares the strings, and Date stringifies as "Mon Mar 02 2026 ...", so the weekday name decides. The same default is why numbers misbehave, as described under Array.prototype.sort.
ISO 8601 strings such as 2026-03-01 sort correctly as plain text, which is a cheap shortcut when the data is already strings in one format. Do not subtract dates that may be invalid: new Date('nope') has a NaN timestamp and breaks the ordering.