Clue Mediator

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

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..!! 🙂