0

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?

3
  • You're missing the closing quotes after quantity. Commented Feb 21, 2014 at 3:24
  • I tried your code and it worked for me. Commented Feb 21, 2014 at 3:27
  • That was after I fixed the quoting around some of the quantity properties. Commented Feb 21, 2014 at 3:30

1 Answer 1

3

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]);
});
Sign up to request clarification or add additional context in comments.

4 Comments

His date properties aren't in a format that new Date() can parse portably.
Date parser is pretty lenient, it will still work. As long as all the dates are in the same format as your locale (in some places its day/month/year).
ok...but none of this explains why hte function above doesn't work
The Date parser is lenient, but different browsers understand different formats. The only format I think you can be sure will work is YYYY-MM-DD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.