How to sort a date string array with JavaScript
📅May 28, 2022
Sometimes we have to sort a date string array in JavaScript. In this article, we will show you how to sort a date string array using JavaScript.
Checkout more articles on JavaScript
- Divide an array in half using JavaScript
- Open base64 Image in a new tab using JavaScript
- How to check if an array is empty or exist in JavaScript
- How to create an auto-resize Textarea in JavaScript
- Check if an array contains all the elements of another array in JavaScript
Here we will use the Date object to sort a date string array. Let’s use the following date array for the demonstration.
const data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
Here, we’ll use the Array.prototype.sort() method with the **Date** constructor.
const sorted = data.sort((a, b) => {
const dtA = a.split('/').reverse().join('-');
const dtB = b.split('/').reverse().join('-');
return new Date(dtA) - new Date(dtB)
})
console.log(sorted);
// ['18/05/2015', '09/06/2015', '22/06/2015', '25/06/2015', '25/07/2015']
If the returned number is negative, then order stays the same. Otherwise, the `a` and `b` are reversed.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂