Javascript - 对包含根据日期升序和降序的对象的嵌套数组进行排序

时间:2016-02-11 06:52:30

标签: javascript arrays json sorting

以下是我的json数据:

var homes={
"ERROR": "SUCCESS",
"DATA": [
    {
        "BookingID": "9513",
        "DutyStart": "2016-02-11 12:00:00"
    },
    {
        "BookingID": "91157307",
        "DutyStart": "2016-02-11 13:00:00"
    },
    {
        "BookingID": "95117317",
        "DutyStart": "2016-02-11 13:30:00"
    },
    {
        "BookingID": "957266",
        "DutyStart": "2016-02-12 19:15:00"
    },
    {
        "BookingID": "74",
        "DutyStart": "2016-02-11 12:21:00"
    }
]
};

我想使用 Javascript 按降序和升序排序按照DutyStart(日期格式)对数组进行排序,并将数据附加到正文或警告已排序的数组。

我尝试了This question的解决方案,但我无法得到它。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您的数据的简单冒泡排序,按日期排序:



var homes={
"ERROR": "SUCCESS",
"DATA": [
    {
        "BookingID": "9513",
        "DutyStart": "2016-02-11 12:00:00"
    },
    {
        "BookingID": "91157307",
        "DutyStart": "2016-02-11 13:00:00"
    },
    {
        "BookingID": "95117317",
        "DutyStart": "2016-02-11 13:30:00"
    },
    {
        "BookingID": "957266",
        "DutyStart": "2016-02-12 19:15:00"
    },
    {
        "BookingID": "74",
        "DutyStart": "2016-02-11 12:21:00"
    }
]
};


var list = homes.DATA.sort(function(a, b) {
    return a.DutyStart - b.DutyStart;
});
console.log(list);




希望这有帮助。

答案 1 :(得分:1)

您可以非常轻松地使用类似ISO 8601的日期字符串sort,因为它们可以像字符串一样工作。

将值传递给sort函数并根据比较返回0,1或-1,例如:

// Data
var homes={
"ERROR": "SUCCESS",
"DATA": [
    {
        "BookingID": "9513",
        "DutyStart": "2016-02-11 12:00:00"
    },
    {
        "BookingID": "91157307",
        "DutyStart": "2016-02-11 13:00:00"
    },
    {
        "BookingID": "95117317",
        "DutyStart": "2016-02-11 13:30:00"
    },
    {
        "BookingID": "957266",
        "DutyStart": "2016-02-12 19:15:00"
    },
    {
        "BookingID": "74",
        "DutyStart": "2016-02-11 12:21:00"
    }
]
};

// Sort - operates on the original array
homes.DATA.sort(function(a, b) {
  return a.DutyStart < b.DutyStart? -1 : (a.DutyStart == b.DutyStart? 0 : 1); 
});

document.write(JSON.stringify(homes.DATA));

答案 2 :(得分:0)

我建议使用String#localeCompare来完成此任务,因为它会比较字符串,而数据是ISO 8601日期字符串,可以使用此方法直接对它们进行排序。

var homes = { "ERROR": "SUCCESS", "DATA": [{ "BookingID": "9513", "DutyStart": "2016-02-11 12:00:00" }, { "BookingID": "91157307", "DutyStart": "2016-02-11 13:00:00" }, { "BookingID": "95117317", "DutyStart": "2016-02-11 13:30:00" }, { "BookingID": "957266", "DutyStart": "2016-02-12 19:15:00" }, { "BookingID": "74", "DutyStart": "2016-02-11 12:21:00" }] };

homes.DATA.sort(function (a, b) {
    return a.DutyStart.localeCompare(b.DutyStart);
});

document.write('<pre>' + JSON.stringify(homes, 0, 4) + '</pre>');