我的问题是关于使用时间和日期进行排序。
这是我的数组对象:
[
{
exercise_description:"SDA",
exercise_id:"13",
exercise_name:"WEIGHT",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"SAMPLE"
},
{
exercise_description:"SDA",
exercise_id:"13",
exercise_name:"ASA",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"kk"
},
{
exercise_description:"dsf",
exercise_id:"14",
exercise_name:"vajrasanam",
exercise_time:"03:45 AM",
workout_date:"2016-02-15",
workout_desc:"rfsgfrds"
},
{
exercise_description:"fds",
exercise_id:"12",
exercise_name:"fsdd",
exercise_time:"01:15 PM",
workout_date:"2016-02-16",
workout_desc:"dda"
}
]
我想对此进行排序,例如
[
{
exercise_description:"dsf",
exercise_id:"14",
exercise_name:"vajrasanam",
exercise_time:"03:45 AM",
workout_date:"2016-02-15",
workout_desc:"rfsgfrds"
},
{
exercise_description:"SDA",
exercise_id:"13",
exercise_name:"WEIGHT",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"SAMPLE"
},
{
exercise_description:"SDA",
exercise_id:"13",
exercise_name:"ASA",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"kk"
},
{
exercise_description:"fds",
exercise_id:"12",
exercise_name:"fsdd",
exercise_time:"01:15 PM",
workout_date:"2016-02-16",
workout_desc:"dda"
}
]
我该如何排序?
答案 0 :(得分:0)
所以我觉得这必须要做到这一点。
var arrayData = [
{ exercise_description:"SDA",
exercise_id:"13",
exercise_name:"WEIGHT",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"SAMPLE"
},
{ exercise_description:"SDA",
exercise_id:"13",
exercise_name:"ASA",
exercise_time:"09:30 AM",
workout_date:"2016-02-15",
workout_desc:"kk"
},
{ exercise_description:"dsf",
exercise_id:"14",
exercise_name:"vajrasanam",
exercise_time:"03:45 AM",
workout_date:"2016-02-15",
workout_desc:"rfsgfrds"
},
{
exercise_description:"fds",
exercise_id:"12",
exercise_name:"fsdd",
exercise_time:"01:15 PM",
workout_date:"2016-02-16",
workout_desc:"dda"
}
];
//this must sort the array as you requested
var sortedData = arrayData .sort(function(a,b){
return new Date(a.workout_date + ' ' + a.exercise_time) - new Date(b.workout_date + ' ' + b.exercise_time);
});
确保使用尽可能多的数据集来检查此逻辑,以确保其稳定。
答案 1 :(得分:0)
在JS日期中,跨浏览器可能会出现问题,momentJS可以使用简单的array.sort方法解决问题。
var sorted = unsorted.sort(function(a,b) {
var aDate = moment(a.workout_date + ' ' +a.exercise_time).unix();
var bDate = moment(b.workout_date + ' ' +b.exercise_time).unix();
if(aDate < bDate) {
return -1;
}
if(aDate > bDate) {
return 1;
}
return 0;
});