我有一些对象:
[{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中实现它?
答案 0 :(得分:2)
您可以使用sort
和Date.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);