Sort an array of dates in JavaScript
Intermediate · 4 min read
A list of orders, blog posts or appointments usually needs to be shown in date order: oldest first for a timeline, newest first for a feed. JavaScript arrays have a sort method, but calling it with no arguments on dates gives an order that looks random.
In this tutorial you will sort an array of dates oldest first and newest first, without changing the original array. Then you will look at the "random" order from plain sort() and work out exactly where it comes from. You need to know what an array is, how to make a date with new Date(year, month, day), and that months count from 0.
How sort decides the order
sort can take a comparator: a function that receives two items, x and y, and returns a number.
- A negative number means
xgoes first. - A positive number means
ygoes first. - Zero means they are equal, so either order is fine.
For numbers, (x, y) => x - y does all three: if x is smaller, x - y is negative, so x goes first. That gives smallest first.
If you don't pass a comparator, sort turns every item into a string and sorts the strings alphabetically. That is fine for words and wrong for almost everything else.
Dates subtract into numbers
When you subtract two dates, JavaScript turns each into its timestamp, the number of milliseconds since 1970, and subtracts those. An earlier date has a smaller timestamp, so x - y works as a comparator for dates too.
To print the results, this tutorial uses iso, a small helper that turns a date into YYYY-MM-DD text:
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
Here is the exercise. Try it on your own first if you like, then read on and we will build it step by step.
30 Sort an array of dates
fairSort dates oldest first. Then run sort() with no comparator on the same array and explain the order you get.
Stuck? Three hints, smallest first
- 1.
sort((a, b) => a - b)works, because subtracting two dates gives a number. - 2.
sort()with no comparator converts every element to a string first. - 3. A date’s string form starts with the weekday name, so the default sort is alphabetical by weekday.
Step 1: sort oldest first
Start with three dates, out of order:
const dates = [new Date(2026, 2, 1), new Date(2026, 0, 15), new Date(2026, 1, 20)];
const oldestFirst = dates.slice().sort((x, y) => x - y);
console.log(oldestFirst.map(iso).join(' ')); // '2026-01-15 2026-02-20 2026-03-01'
map(iso) turns each date into text, and join(' ') puts them on one line so they are easy to read.
Why slice()? sort changes the array you call it on. slice() with no arguments makes a copy, so the copy gets sorted and dates stays as it was:
console.log(dates.map(iso).join(' ')); // '2026-03-01 2026-01-15 2026-02-20'
Step 2: newest first
Swap x and y in the subtraction to reverse the order:
const newestFirst = dates.slice().sort((x, y) => y - x);
console.log(newestFirst.map(iso).join(' ')); // '2026-03-01 2026-02-20 2026-01-15'
Now a later date gives a negative number, so it goes first.
Step 3: the wrong turn, sort() with nothing
Here is what happens without a comparator:
const noComparator = dates.slice().sort();
console.log(noComparator.map(iso).join(' ')); // '2026-02-20 2026-03-01 2026-01-15'
It is neither oldest first nor newest first. To see why, look at the start of each date's string form:
console.log(dates.map((d) => String(d).slice(0, 3)).join(' ')); // 'Sun Thu Fri'
A date's text form starts with the weekday: Sun Mar 01 2026 ..., Thu Jan 15 2026 ..., Fri Feb 20 2026 .... Sorted alphabetically, F comes before S, and S before T. So plain sort() put the dates in order of the name of the weekday. That is why it looks like a shuffle.
Step 4: getTime says the same thing
If you'd rather be explicit, compare the timestamps yourself:
const explicit = dates.slice().sort((x, y) => x.getTime() - y.getTime());
console.log(explicit.map(iso).join(' ')); // '2026-01-15 2026-02-20 2026-03-01'
It gives the same result as x - y. Some people prefer it because it makes clear that the comparison is on numbers.
Step 5: ISO text sorts correctly
There is one kind of date text that does sort correctly as plain strings: YYYY-MM-DD. The biggest unit comes first, and every part has a fixed width, so alphabetical order is date order:
console.log(dates.map(iso).sort().join(' ')); // '2026-01-15 2026-02-20 2026-03-01'
This is one reason dates are often stored as ISO text in files and databases.
The full solution
The panel sorts the three dates oldest first and newest first, shows the plain sort() order with the weekday names that explain it, and checks the getTime and ISO text versions. Press Run to see the output.
const iso = (d) => d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
const dates = [new Date(2026, 2, 1), new Date(2026, 0, 15), new Date(2026, 1, 20)];
// slice() first: sort mutates the array it is given.
const oldestFirst = dates.slice().sort((x, y) => x - y);
const newestFirst = dates.slice().sort((x, y) => y - x);
const noComparator = dates.slice().sort();
console.log('as given :', dates.map(iso).join(' '));
console.log('oldest first:', oldestFirst.map(iso).join(' '));
console.log('no comparator:', noComparator.map(iso).join(' '), '<- alphabetical');
console.log('why:', dates.map((d) => String(d).slice(0, 3)).join(' '), '-> Fri, Sun, Thu sorts F, S, T');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('oldest first', oldestFirst.map(iso), ['2026-01-15', '2026-02-20', '2026-03-01']);
test('newest first', newestFirst.map(iso), ['2026-03-01', '2026-02-20', '2026-01-15']);
test('the source array was not touched', dates.map(iso), ['2026-03-01', '2026-01-15', '2026-02-20']);
test('no comparator sorts by the string form, which starts with the weekday', noComparator.map(iso), ['2026-02-20', '2026-03-01', '2026-01-15']);
test('so it is not chronological', same(noComparator.map(iso), oldestFirst.map(iso)), false);
test('comparing timestamps explicitly gives the same answer as subtraction', dates.slice().sort((x, y) => x.getTime() - y.getTime()).map(iso), oldestFirst.map(iso));
test('sorting the ISO strings as text also works', dates.map(iso).slice().sort(), oldestFirst.map(iso));
test('one date sorts to itself', [new Date(2026, 0, 15)].sort((x, y) => x - y).map(iso), ['2026-01-15']);
sort((a, b) => a - b) is the answer. Subtraction converts both dates to numbers, so the comparator is a plain numeric one.
The default sort() is the interesting failure. It converts each element with String() and compares the results as text, and a date's string form begins with the abbreviated weekday: Fri Feb 20 2026, Sun Mar 01 2026, Thu Jan 15 2026. Alphabetically that is F, S, T — so the array comes back sorted by the name of the day, which looks like a shuffle. The last assertion shows the alternative worth knowing: ISO strings sort correctly as plain text, which is why ISO is the right storage format.
Common mistakes
- Calling
sort()with no comparator. It sorts the text forms, which start with the weekday name. - Forgetting that
sortchanges the array. Sort a copy made withslice()if you still need the original order. - Sorting text like
15/01/2026. Day-first text sorts by day, not by date. Sort the dates, or useYYYY-MM-DDtext.
Try it yourself
- Sort an array of objects like
{ title, publishedAt }bypublishedAt, newest first. - Add a fourth date that equals one of the others. Where does it end up?
- Sort
['15/01/2026', '01/03/2026', '20/02/2026']as text. Then convert each to a date and sort again. Compare the two results.