0

我正在尝试对日期列上的多维数组进行排序。每行中的第一个日期是开始日期,第二个是结束日期。我想根据开始日期按升序对行进行排序。

数据结构为:

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);

我尝试了这里建议的所有可能的解决方案,但没有运气。我可能在这里忽略了一些简单的错误。非常感谢任何帮助。

4

1 回答 1

1

您的代码有 2 个问题: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);
于 2013-10-20T09:25:18.243 回答