- Published on
Sorting Dates in Javascript using Array.sort method
- Authors
- Name
- Ashik Nesin
- @AshikNesin
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 Value | Order |
---|---|
> 0 | Ascending order |
< 0 | Descending order |
=== 0 | Keep 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