2

In AJAX response I am getting JSON array with multiple nodes. How can I sort every node by its time stamp .

Code I tried:

$$.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                                            
            }   
        }); 

Also value of jsondata1 is

    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"}

]

Sorting it by (created_at) Error I am getting is

"Uncaught TypeError: jsondata1.sort is not a function".

Nehil Mistry
  • 1,101
  • 2
  • 22
  • 51

1 Answers1

1

You can treat date strings (in this case as ISO format) as string and sort it with 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>');

For different date type I suggest to have a look here: Sort Javascript Object Array By Date

Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392