Rishabh Rishabh - 10 days ago 7
Javascript Question

sort an array containing dates in dd-mmm-yy format

I am trying to sort an array which contains dates in string format (dd-mmm-yy), using the

sort()
function:

var array = ["1-jun-15", "1-feb-15", "1-apr-15", "1-may-15", "1-jan-15", "1-mar-15"];

array.sort(function(a, b) {
return new Date(a.date).getTime() - new Date(b.date).getTime();
});


But no success.

What's going wrong here? Here is the JSFiddle.

Answer

You were very very close

array.sort(function(a, b) {
  let aa = new Date(a)
  let bb = new Date(b)
  return aa.getTime() - bb.getTime();
});