javascript - 按日期javascript对JSON数据进行排序

标签 javascript angularjs json sorting

我正在尝试按日期 对我的json 数据 进行排序,但它不起作用。这就是我正在尝试的。请纠正我错误的地方

示例代码

var temp = [{
    "id": 17608,
    "title": "abc",
    "start": "2016-03-23 06:13:00.0",
    "backgroundColor": "#000000",
    "borderColor": "#000000",
    "textColor": "#fff"
}, {
    "id": 17608,
    "title": "def",
    "start": "2016-04-13 06:13:00.0",
    "backgroundColor": "#000000",
    "borderColor": "#000000",
    "textColor": "#fff"
}, {
    "id": 17608,
    "title": "ghi",
    "start": "2016-04-08 06:13:00.0",
    "backgroundColor": "#000000",
    "borderColor": "#000000",
    "textColor": "#fff"
}];

console.log(temp);

temp.sort(function(a, b) {
    if (new Date(a.start) == new Date(b.start)) {
        return a.row == b.row ? 0 : +a.row > +b.row ? 1 : -1;
    }

    return new Date(a.start) > (b.start) ? 1 : -1;
});

console.log(temp);

最佳答案

您可以使用日期字符串进行排序,而它是一个ISO 6801。日期。

var temp = [{ "id": 17608, "title": "abc", "start": "2016-03-23 06:13:00.0", "backgroundColor": "#000000", "borderColor": "#000000", "textColor": "#fff" }, { "id": 17608, "title": "def", "start": "2016-04-13 06:13:00.0", "backgroundColor": "#000000", "borderColor": "#000000", "textColor": "#fff" }, { "id": 17608, "title": "ghi", "start": "2016-04-08 06:13:00.0", "backgroundColor": "#000000", "borderColor": "#000000", "textColor": "#fff" }];

temp.sort(function (a, b) {
    return a.start.localeCompare(b.start);
});

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

关于javascript - 按日期javascript对JSON数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36444492/

相关文章:

javascript - 单击标记时不显示 react 传单弹出窗口

javascript - 如何将我的 javascript 从内联文件更改为外部文件?

javascript - 在 Chrome 上渲染 pdf blob

ajax - Cappuccino 、Django、AJAX 并将它们组合在一起 - 回顾我的架构!

javascript - angularjs重启css动画

javascript - 推送到具有 __proto__ 的 Javascript 数组

javascript - 通过开放模态函数 Angular uibModal 传递数据

php - 如何创建像 Stripe checkout 这样的弹出窗口

java - 从 XAgent 创建 Json

javascript - 如何将 JSON 转换为数组并在 jQuery 中对其进行循环?