-1

I have a function that gets JSON from an API (fetched with PHP). I can't figure out I'd sort the data by payload.time. The JSON is in random order, so .reverse() doesn't do any good ether. I'm wondering how is it possible to sort the following JSON in order by time?

{
   "code":0,
   "payload":[
      {
         "time":1349661897,
         "packages":[
            "49381"
         ],
         "ign":"player1",
         "price":"15.99",
         "currency":"USD"
      },
      {
         "time":1354504024,
         "packages":[
            "33109"
         ],
         "ign":"player2",
         "price":"6.99",
         "currency":"USD"
      }
}

Here's my JS:

var Donors = function(api) {

   this.list = api;

   $.each(this.list.payload.slice(0, 25), function(i, donor) {
     var ign = donor.ign,
       price = donor.price,
       currency = donor.currency,
       el = '<li id="' + ign + '" class="player big" data-player="' + ign + '" title="'+ ign + ' // ' + price + ' ' + currency + '">☺</li>';
      if(price !== "-") $('#donors').append(el);

    });
}
devs
  • 541
  • 2
  • 13
  • 27

1 Answers1

0

You can write a function to sort JSON array :

function sortBy(jsonArray, key){
    if(jsonArray){
       var sortedArray = jsonArray.sort(function(left, right) { 
                         //array.sort is buit-in function
           var a = left[key];
           var b = right[key];
           if (a !== b) {
               if (a > b || a === void 0) return 1;
               if (a < b || b === void 0) return -1;
           }
           return 0;
      });
      return sortedArray;
    }
}

call this function with :

sortBy(payload, 'time')

Note: Code snippet is not tested.

Jaynti Kanani
  • 557
  • 6
  • 23