简体   繁体   English

日期上的JavaScript排序功能不起作用

[英]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? 为什么?

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. DD/MM/YYYY应该被日期解析器接受,这是溢出的版本。

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]);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM