我有一个未排序格式的数组。 即
var _dateArray = [
{ startTime : 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 17:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 19:15:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 21:00:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 16:45:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 17:15:00 GMT+0530 (IST)' },
];
我想按照这种格式对此数组进行排序
var _dateArray = [
{ startTime : 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 16:45:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 17:15:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 17:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 19:15:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' },
{ startTime : 'Sat Feb 21 2015 20:00:00 GMT+0530 (IST)' ,endTime : ' Sat Feb 21 2015 21:00:00 GMT+0530 (IST)' },
];
你能告诉我如何实现这项功能吗?
感谢。
答案 0 :(得分:1)
您需要将JavaScript函数.sort()
与自定义比较器一起使用,您将在其中解析开始日期并进行比较。
自定义比较器是一个接收2个项目的函数,并根据您的自定义比较要求返回负值/零/正值。 .sort()
函数使用提供的比较器并使用它来比较排序期间的元素:
var _dateArray = [{
startTime: 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)'
}, {
startTime: 'Sat Feb 21 2015 19:00:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 20:00:00 GMT+0530 (IST)'
}, {
startTime: 'Sat Feb 21 2015 17:00:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 19:15:00 GMT+0530 (IST)'
}, {
startTime: 'Sat Feb 21 2015 20:00:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 21:00:00 GMT+0530 (IST)'
}, {
startTime: 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 16:45:00 GMT+0530 (IST)'
}, {
startTime: 'Sat Feb 21 2015 16:30:00 GMT+0530 (IST)',
endTime: ' Sat Feb 21 2015 17:15:00 GMT+0530 (IST)'
}];
//this is our comparator function
function DateComparator(dateAPair, dateBPair) {
var DateA = new Date(dateAPair.startTime);
var DateB = new Date(dateBPair.startTime);
if (DateA < DateB) {
return -1;
} else if (DateA > DateB) {
return 1;
} else {
return 0;
}
}
console.log(_dateArray);
_dateArray.sort(DateComparator);
console.log(_dateArray);