Sort a string date array

The Simple Solution

There is no need to convert Strings to Dates or use RegExp.

The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.

data.sort(function(a,b) {
  a = a.split("https://stackoverflow.com/").reverse().join('');
  b = b.split("https://stackoverflow.com/").reverse().join('');
  return a > b ? 1 : a < b ? -1 : 0;
  // return a.localeCompare(b);         // <-- alternative 
});

Update:

A helpful comment suggested using localeCompare() to simplify the sort function. This alternative is shown in the above code snippet.

Run Snippet to Test

<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
  var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];

data.sort(function(a,b) {
  a = a.split("https://stackoverflow.com/").reverse().join('');
  b = b.split("https://stackoverflow.com/").reverse().join('');
  return a > b ? 1 : a < b ? -1 : 0;
  
  // return a.localeCompare(b);         // <-- alternative 
  
});

for(var i=0; i<data.length; i++) 
  stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

Leave a Comment