Skip to content
jshacks.dev
Fundamentals

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.

1 min read
Summarize in AI

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.

JavaScript
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()));
Text
[ '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.

Taggednode 24
Share

More snippets

Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read
Fundamentals

Create a URL with search params

Build a URL with query parameters using URL and searchParams, and see how spaces and ampersands are encoded, plus how to resolve a relative path. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.