Skip to content
Advertisement

How to sort the string of date format in an array

Input

var data = ["09 may 2015", "25 december 2015", "22 march 2015", "25 june 2016", "18 august 2015"];

output 22 March 2015, 09 May 2015, 18 August 2015, 25 December 2015, 25 jun 2016

Advertisement

Answer

Subtracting 2 dates returns the difference between the two dates in milliseconds if a date is smaller than b returns negative values a will sorted to be a lower index than b.

var data = ["09 may 2015", "25 december 2015", "22 march 2015", "25 june 2016", "18 august 2015"];


data.sort(function(a,b){
  return  new Date(a) - new Date(b);
});
console.log(data);
Advertisement