0

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 ?

wawanopoulos
  • 9,614
  • 31
  • 111
  • 166

2 Answers2

2

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    It wouldn't matter if they were strings (e.g. `date : "1414836094"`), the `-` operator coerces the values to Number. The example would be better if the dates weren't sorted to start with. ;-) – RobG Dec 09 '15 at 14:22
0
var sorted = jsonList.inventory.sort(function(a,b) {
   return a.date < b.date ? -1 : 1;
});
Arnaud Gueras
  • 2,014
  • 11
  • 14
  • 1
    What about if `a == b`? Maybe `return a.date - b.date`. – RobG Dec 09 '15 at 14:20
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – ryanyuyu Dec 09 '15 at 15:27