我正在尝试对日期列上的多维数组进行排序。每行的第一个日期是开始日期,第二个日期是结束日期。我想根据开始日期按升序对行进行排序。
数据结构是:
data = [["p1aprd", "Monthly", "PRD", "Date {Wed Nov 06 2013 01:27:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 07 2013 01:28:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Tue Nov 05 2013 01:29:00 GMT-0800 (Pacific Daylight Time)}", "Date {Wed Nov 06 2013 01:29:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Mon Nov 04 2013 01:31:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 14 2013 01:31:00 GMT-0800 (Pacific Daylight Time)}", "2"],
["p1aprd", "Monthly", "PRD", "Date {Mon Nov 04 2013 01:00:00 GMT-0800 (Pacific Daylight Time)}", "Date {Thu Nov 14 2013 01:38:00 GMT-0800 (Pacific Daylight Time)}", "2"]];
我正在尝试这个功能:
data.sort((function(index){
return function(a, b){
return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};})(4));
alert(data);
我尝试了所有可能的解决方案,但没有运气。我可能会在这里忽略一些简单的错误。任何帮助都非常感谢。
答案 0 :(得分:1)
您的代码有两个问题: 1.您正在比较日期字符串而不是日期。 2.你传递的是4,而开始日期的索引是3。
试试这个:
function getDateFromString(str){ return new Date(str.match(/\{(.*) \(/)[1]); }
data.sort((function(index){
return function(a, b){
a = getDateFromString(a[index]);
b = getDateFromString(b[index]);
return a - b;
};
})(3));
alert(data);