Sometimes, we want to sort a date string array with JavaScript.
In this article, we’ll look at how to sort a date string array with JavaScript.
How to sort a date string array with JavaScript?
To sort a date string array with JavaScript, we can use the JavaScript date’s sort
method.
For instance, we write:
const data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
const sorted = data.sort((a, b) => {
const newA = a.split('/').reverse().join('-');
const newB = b.split('/').reverse().join('-');
return +new Date(newA) - +new Date(newB)
})
console.log(sorted)
We call data.sort
with a function that gets the date strings and change their format to something that can used with the Date
constructor.
Then we create date objects from each of them, convert them to timestamps, and subtract them to return the number to determine the sorting.
If the returned number is negative, then order stays the same. Otherwise, the a
and b
are reversed.
Therefore, sorted
is ['18/05/2015', '09/06/2015', '22/06/2015', '25/06/2015', '25/07/2015']
.
Conclusion
To sort a date string array with JavaScript, we can use the JavaScript date’s sort
method.