praks5432
praks5432

Reputation: 7792

Javascript sort function on dates not working

So I have this code -

console.log(data);
data = data.sort(function(d1,d2){
     var a1= d1["date"].split('/'), b1=d2["date"].split('/');
      if(a1[2]==b1[2]){
        return (a1[0]==b1[0])? a1[1]-b1[1]: a1[0]-b1[0];
      }
      return a1[2]-b1[2];
});
console.log("DATA");
console.log(data);

with this data -

[
{ "date": "2/7/2012", "quantity: " 4"},
{ "date": "2/4/2012", "quantity: "5"},
{ "date": "2/3/2012", "quantity: "10"},
{ "date": "2/5/2012", "quantity" : "12"},
{ "date": "2/6/2012", "quantity" : "10"}
]

The two console logs show the data in the same way, or the sorting has no effect. The data coming out of the sort function is in the same order as the data going in.

Why?

Upvotes: 0

Views: 387

Answers (1)

xdazz
xdazz

Reputation: 160833

Try:

data = data.sort(function(d1,d2){
  return new Date(d1.date) - new Date(d2.date);
});

DD/MM/YYYY should be acceptable by Date parser, here is the spilt version.

data = data.sort(function(d1, d2){
  var d1 = d1.split('/'), d2 = d2.split('/');
  return new Date(d1[2], d1[0] - 1, d1[1]) - new Date(d2[2], d2[0] - 1, d2[1]);
});

Upvotes: 3

Related Questions