Published on

Sorting Dates in Javascript using Array.sort method


Let's say you've an array of date that needs to sorted without using any third party library.

For such use cases we can use Array.sort()

const input = [

const ascendingOrder = input.sort((a, b) => new Date( - new Date(;

const descendingOrder = input.sort((a, b) => new Date( - new Date(;


Sort method takes in a compare function which has params (first and second item). Depending on it's return value the items in the array are sorted.

Return ValueOrder
> 0Ascending order
< 0Descending order
=== 0Keep it as it is

In Javascript, when you subtract a number from a Date it'll return a number of milliseconds between the two dates.

For example, new Date() - 1 will subtract one millisecond from your current date and time. As like other programming languages the time is counted from January 1, 1970, 00:00:00 UTC (starting point for Unix time) as beginnning time.

Happy sorting dates