wawanopoulos
wawanopoulos

Reputation: 9804

Sort an array of object by timestamp

I have the following object :

var jsonList = {
   ref : "TEST1",
   inventory : [
         {
            id : "a1",
            date : 1401462270
         },
         {
            id : "a2",
            date : 1414836094
         }
   ]
}

inventory array is not sorted by date, i would like to sort this array of object by date. The more recent in first position.

How can i do that ?

Upvotes: 0

Views: 7734

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386634

While there are integers, you can return the difference for comparing.

var jsonList = { ref: "TEST1", inventory: [{ id: "a1", date: 1401462270 }, { id: "a2", date: 1414836094 }] },
    sorted = jsonList.inventory.sort(function(a, b) {
        return a.date - b.date;
    });

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

Upvotes: 2

Arnaud Gueras
Arnaud Gueras

Reputation: 2062

var sorted = jsonList.inventory.sort(function(a,b) {
   return a.date < b.date ? -1 : 1;
});

Upvotes: 0

Related Questions