订单数组如何按日期和时间递减?

时间:2016-06-02 08:30:52

标签: javascript lodash

我有一些对象:

[{id:'124',name:'ttt', MeasureDate:"2015-04-05T18:46:38"}, 
 {id:'589',name:'mmm', MeasureDate:"2015-05-05T18:46:38"}, 
 {id:'45',name:'yyy' , MeasureDate:"2016-01-05T18:46:38"},
 {id:'567',name:'eee', MeasureDate:"2016-05-05T18:46:38"}]

我需要按照date and time降序排列数组:

[{id:'567',name:'eee', MeasureDate:"2016-05-05T18:46:38"},
 {id:'45',name:'yyy' , MeasureDate:"2016-01-05T18:46:38"},
 {id:'589',name:'mmm', MeasureDate:"2015-05-05T18:46:38"},
 {id:'124',name:'ttt', MeasureDate:"2015-04-05T18:46:38"}]

如何在javascript中实现它?

2 个答案:

答案 0 :(得分:2)

您可以使用sortDate.parse

var data = [{id:'124',name:'ttt', MeasureDate:"2015-04-05T18:46:38"}, 
 {id:'589',name:'mmm', MeasureDate:"2015-05-05T18:46:38"}, 
 {id:'45',name:'yyy' , MeasureDate:"2016-01-05T18:46:38"},
 {id:'567',name:'eee', MeasureDate:"2016-05-05T18:46:38"}];
 
var sorted = data.sort(function(a, b) {
  return Date.parse(b.MeasureDate) - Date.parse(a.MeasureDate);
});

console.log(sorted)

答案 1 :(得分:1)

只需使用sort String#localeCompare对其进行排序。

这是可能的,而日期是ISO6801,这是一个可排序的字符串。

var array = [{id:'124',name:'ttt', MeasureDate:"2015-04-05T18:46:38"}, {id:'589',name:'mmm', MeasureDate:"2015-05-05T18:46:38"}, {id:'45',name:'yyy', MeasureDate:"2016-01-05T18:46:38"}, {id:'567',name:'eee', MeasureDate:"2016-05-05T18:46:38"}];

array.sort(function (a, b) {
    return b.MeasureDate.localeCompare(a.MeasureDate);
});

console.log(array);