在jquery中按时间戳排序数组

时间:2015-11-21 11:05:30

标签: javascript android jquery arrays json

在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)我得到的错误是

  

“Uncaught TypeError:jsondata1.sort不是函数”。

1 个答案:

答案 0 :(得分:1)

您可以将日期字符串(在本例中为ISO format)视为字符串,并使用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>');

对于不同的日期类型,我建议您查看:Sort Javascript Object Array By Date