Introduction
In this short guide, we'll cover all necessary aspects of sorting an array by date in JavaScript.
The array data structure in JavaScript has a built-in sort()
method, but it is not designed to be used to sort an array by date. There are a lot of different date formats and we need to make the sorting work no matter the format used to represent a date.
Firstly, let's go into some basic concepts and constraints that we need to understand to be able to alter the sort()
method so that it can sort the elements of an array by date, and then we'll show some practical examples that explain how sorting by dates works.
Note: In this guide, we'll be sorting an array of dates, but the same rules apply in the case of sorting an array of objects containing a date property
JavaScript's sort() method
As previously mentioned, the Array
data structure in JavaScript has a built-in sort()
method used to sort the elements of an array. The sort()
method works by converting the elements into strings and sorting those string representations of elements lexicographically in ascending order.
Another important fact to keep in mind is that the sort()
method sorts elements in-place, meaning that it alters the original array:
const exampleArray = ['bbb', 'aa', 'ddd', 'c'];
exampleArray.sort();
console.log(exampleArray);
// Outputs: ['aa', 'bbb', 'c', 'ddd']
Obviously, the sort()
method is designed to work with strings, but it is not designed to work with dates. For example, let's assume that we want to sort the following array of dates:
const dates = ['Mar 16 2017', 'Jan 22 2021', 'Dec 31 2000'];
dates.sort();
console.log(dates);
The desired output will be an array sorted by dates in ascending order:
['Dec 31 2000', 'Mar 16 2017', 'Jan 22 2021']
But the actual output will be:
['Dec 31 2000', 'Jan 22 2021', 'Mar 16 2017']
This happens because the sort()
method works by sorting the string representations of elements, not the actual elements.
For instance, D
from 'Dec 31 2000'
is lexicographically lesser than J
from 'Jan 22 2021'
and so on. This undesired behavior is the same no matter the date format, therefore, we need to find a way to alter the sort()
method to make it suitable for sorting dates.
Primer on Dates in JavaScript
In order to know how to sort an array by date in JavaScript, firstly, we need to understand how JavaScript represents dates.
In short, the structure used to represent dates in JavaScript is a Date
object, it does so by storing a Number
that represents the number of milliseconds since 1 January 1970.
There are four ways of creating a Date
object, but, in essence, all of them store the date as the Number
, as previously described:
// Blank constructor - the current date and time
const now = new Date();
// Date string as the argument
const exampleDate1 = new Date(dateString);
// Number of milliseconds since 1 Jan 1970 as the argument
const exampleDate2 = new Date(milliseconds);
// Year, month, ... as the argument
const exampleDate3 = new Date(year, month, day, hour, minute, second, millisecond);
Due to the nature of the problem of sorting an array by date, we'll use the second way, passing the string representation of the date in the Date
constructor. Generally speaking, there are 3 formats of strings that are used to represent dates:
Name | Format | Example | Browser Independent |
ISO Date | YYYY-MM-DD | "2017-09-24" | **Yes** (strictly defined by ISO standard) |
Short Date | MM/DD/YYYY | "09/24/2017" | **No** (may vary on different browsers) |
Long Date | DD Month YYYY | "24 September 2017" | **No** (may vary on different browsers) |
So, if we want to create a Date
object for the 24th of September 2017, we'll do so in one of the following ways:
const date = new Date("2017-09-24");
// Or
const date = new Date("09/24/2017");
// Or
const date = new Date("24 September 2017");
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
All of these will represent the exact same date (the same number of milliseconds since 1 January 1970).
How to Sort an Array by Date in JavaScript (String Representation)
Now that we know how does the Date
object and sort()
method work, we can explain how to use the sort()
method to sort an array by a date.
Firstly, let's assume that we need to sort an array of dates:
// ['16 March 2017', '22 January 2021', '31 December 2000']
const dates = ['16 March 2017', '01/22/2021', '2000-12-31'];
As we can see, elements of the dates
array are string representations of some dates. As we've discussed before, simply using the sort()
method on dates
won't produce the desired output, so we need to alter it to make it suitable for sorting dates. We'll do so by creating an appropriate custom comparison function and passing it to the sort()
method.
A comparison function, in simple terms, is a function that accepts two arguments (numbers) and returns positive, negative, or zero values. It is used to define the sorting order in a sort()
method.
For example, the following comparison function will be used for sorting elements in ascending order:
function(a, b){
return a - b;
}
The following rules apply to the sorting order based on the return value of a compare function:
Return value | Sorting order |
Positive | b before a |
Zero | same |
Negative | a before b |
The comparison function that will be able to sort dates must firstly convert string representations of dates into Date
objects and then compare two dates in the desired way. Thankfully, the Date
constructor accepts a wide variety of formats, and can translate them to an easily comparable format:
function(a, b){
// Convert string dates into `Date` objects
const date1 = new Date(a);
const date2 = new Date(b);
return date1 - date2;
}
For sorting in descending order, the only change we need to make is to swap places of date1
and date2
in the return statement:
return date2 - date1;
When we've created the appropriate comparison function, the only thing left to do is to pass it to the sort()
method in order for it to be able to sort dates:
dates.sort(function(a, b){
const date1 = new Date(a)
const date2 = new Date(b)
return date1 - date2;
})
Alternatively, you can define the function as a non-anonymous function and pass it that way:
function dateComparison(a, b) {
const date1 = new Date(a)
const date2 = new Date(b)
return date1 - date2;
}
dates.sort(dateComparison);
console.log(dates);
Now, the dates
array is sorted in the ascending order:
['2000-12-31', '16 March 2017', '01/22/2021']
How to Sort an Array by Date in JavaScript (Date Objects)
The simpler version of this problem is the case where the dates
array is already an array of Date
objects. In that case, the simplest compare function will do the job:
const date1 = new Date('16 March 2017');
const date2 = new Date('01/22/2021');
const date3 = new Date('2000-12-31');
const dates = [date1, date2, date3];
dates.sort(function(a, b){
return a - b
});
console.log(dates);
The output will be:
['2000-12-31', '16 March 2017', '01/22/2021']
Conclusion
In this guide, we've discussed the important facts about sorting an array by date. Finishing it, you should have the knowledge of sorting arrays, Date
objects, and you are able to combine what you have learned to sort an array of dates in the desired order.