Published on

Sorting Dates in Javascript using Array.sort method

Authors

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 = [
    {"date":"2022-12-07"},
    {"date":"2022-09-30"}
]

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

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

Context

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