JSON, sort by totalSessionsPlayed and output top 3

I'm trying to sort my json by "totalSessionsPlayed" and then output the top 3 into my div "show".

I think as long as I can sort the JSON (which I have no idea how to do), I can then just output the very first 3 objects.

fiddle: https://jsfiddle.net/jzhang172/wjL0wL5b/1/

var homes =  [{
   "modifyDate": 1460338936000,
   "champions": [
      {
         "id": 40,
         "stats": {
            "totalDeathsPerSession": 11,
            "totalSessionsPlayed": 4,
            "totalDamageTaken": 62347,
            "totalQuadraKills": 0,
            "totalTripleKills": 0,
            "totalMinionKills": 57
           
         }
      },
      {
         "id": 75,
         "stats": {
            "totalDeathsPerSession": 6,
            "totalSessionsPlayed": 1,
            "totalDamageTaken": 44536,
            "totalQuadraKills": 0,
            "totalTripleKills": 0,
            "totalMinionKills": 222
         }
      },
      {
         "id": 113,
         "stats": {
            "totalDeathsPerSession": 18,
            "totalSessionsPlayed": 2,
            "totalDamageTaken": 104626,
            "totalQuadraKills": 0,
            "totalTripleKills": 0,
            "totalMinionKills": 94
         }
      },
      {
         "id": 9,
         "stats": {
            "totalDeathsPerSession": 30,
            "totalSessionsPlayed": 7,
            "totalDamageTaken": 174482,
            "totalQuadraKills": 0,
            "totalTripleKills": 0,
            "totalMinionKills": 239
         }
      },
      {
         "id": 254,
         "stats": {
            "totalDeathsPerSession": 9,
            "totalSessionsPlayed": 1,
            "totalDamageTaken": 27748,
            "totalQuadraKills": 0,
            "totalTripleKills": 0,
            "totalMinionKills": 26
         }
      }]
      }
      ];

document.getElementById('show').innerHTML=homes[0].champions[0].id + ' '+homes[0].champions[1].id+ ' '+homes[0].champions[2].id;
<div id="show"></div>

Answers 1

  • You can sort your object with this code:

    homes[0].champions.sort(function(a, b) {
        return parseFloat(a.stats.totalSessionsPlayed) - parseFloat(b.stats.totalSessionsPlayed);
    });
    

    For descending order, you need to switch a.stats.totalSessionsPlayed and b.stats.totalSessionsPlayed


Related Articles