在jquery中按时间戳对数组进行排序

Sort array by timestamp in jquery

本文关键字:数组 排序 时间戳 jquery      更新时间:2023-09-26

在AJAX响应中,我得到了具有多个节点的JSON数组。如何根据每个节点的时间戳对其进行排序。

我尝试过的代码:

$$.ajax({
            type:'POST',
            url: "http://www.xyz.co/get_all_news.php",
            dataType: "JSON",
            data:{'email': window.localStorage["email"], 'business_id': localStorage.getItem("business_id")},
            success: function (jsondata1){
                    data= JSON.parse(jsondata1);
                    jsondata1.sort(function(x, y){
                        return x.created_at - y.created_at;
                    })
                    console.log(jsondata1);   //Error - Uncaught TypeError: jsondata1.sort is not a function                                            
            }   
        }); 

jsondata1的值也是

    var jsondata1 = [
{"id":"1","body":"Bsjd djjdjd jdjdkd djjdjd jdjd","votes":"4","update_type":"7","created_at":"2015-11-21 02:03:41","name":"Nehil"},
{"id":"2","body":"#TestingBestNominations","votes":"1","update_type":"7","created_at":"2015-11-21 02:03:44","name":"Nehil"},
{"id":"1","name":"#milestone1","date":"0000-00-00","location":"Mumbai","story_body":"Hdjjdjdbj djfjjd djkdjd","short_link":"A0Ijv","created_at":"2015-11-19 05:09:41","path":"'/SupportData'/ImpalzB2B'/uploads'/90294930451447934978817.jpg","update_type":"3"},
{"id":"1","name":"Product 1","description":"Dbbxbxjjd fjkd","short_link":"CmR0X","created_at":"2015-11-19 05:28:34","path":"'/SupportData'/ImpalzB2B'/uploads'/90294930451447936111369.jpg","update_type":"4"}
]

按(created_at)排序我得到的错误是

"未捕获的类型错误:jsondata1.sort不是函数"。

您可以将日期字符串(在本例中为ISO格式)视为字符串,并使用String.prototype.localeCompare进行排序。

var jsondata1 = [
        { "id": "1", "body": "Bsjd djjdjd jdjdkd djjdjd jdjd", "votes": "4", "update_type": "7", "created_at": "2015-11-21 02:03:41", "name": "Nehil" },
        { "id": "2", "body": "#TestingBestNominations", "votes": "1", "update_type": "7", "created_at": "2015-11-21 02:03:44", "name": "Nehil" },
        { "id": "1", "name": "#milestone1", "date": "0000-00-00", "location": "Mumbai", "story_body": "Hdjjdjdbj djfjjd djkdjd", "short_link": "A0Ijv", "created_at": "2015-11-19 05:09:41", "path": "'/SupportData'/ImpalzB2B'/uploads'/90294930451447934978817.jpg", "update_type": "3" },
        { "id": "1", "name": "Product 1", "description": "Dbbxbxjjd fjkd", "short_link": "CmR0X", "created_at": "2015-11-19 05:28:34", "path": "'/SupportData'/ImpalzB2B'/uploads'/90294930451447936111369.jpg", "update_type": "4" }
    ];
jsondata1.sort(function (a, b) { return a.created_at.localeCompare(b.created_at); });
document.write('<pre>' + JSON.stringify(jsondata1, 0, 4) + '</pre>');

对于不同的日期类型,我建议在这里查看:按日期排序Javascript对象数组