0

the below code creates the leaderboard for my completed game, the only thing that I can't get it to do is automatically sort the score high to low. I think I need to put the objects into an array and then sort them, just not sure how.

function createLeaderboard() {
        var html;
        html = "<table>";
        html += "<tbody>";
        html += "<th>Username</th>";
        html += "<th>Rank</th>";
        html += "<tr>";

    for(var val in localStorage){


        if (localStorage.getItem(val) !== null && localStorage.getItem(val) !== localStorage.getItem('UsrLoggedIn')){
            var rankData = $.parseJSON(localStorage.getItem(val));

            //console.log(rankData); This will allow you to see the rank data object in your console

            $(rankData).each(function() {                   
                html += "<td>" + rankData.username + "</td>"; 
                html += "<td>" + rankData.rank + "</td> </tr>"; 
            });
        }

    }
    html += "</tbody>";
    html += "</table>";

    $('#rank').append(html);
Adicode
  • 1
  • 1
  • Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Brenden Dec 14 '18 at 01:30
  • Lodash is good for this too: https://stackoverflow.com/questions/22928841/lodash-multi-column-sortby-descending – Nathaniel Flick Dec 14 '18 at 01:42

1 Answers1

1

You can retrieve the rankData first, sort it and finally loop over the sorted array.

function createLeaderboard() {
    var html;
    html = "<table>";
    html += "<tbody>";
    html += "<th>Username</th>";
    html += "<th>Rank</th>";
    html += "<tr>";

    var array = [];
    for (var val in localStorage) {
        if (localStorage.getItem(val) !== null && localStorage.getItem(val) !== localStorage.getItem('UsrLoggedIn')) {
            array.push($.parseJSON(localStorage.getItem(val)));
        }
    }

    array.sort(function (a, b) {
        return a.rank - b.rank;
    });

    array.forEach(function (rankData) {
        html += "<td>" + rankData.username + "</td>";
        html += "<td>" + rankData.rank + "</td> </tr>";
    });

    html += "</tbody>";
    html += "</table>";

    $('#rank').append(html);
}
Ele
  • 33,468
  • 7
  • 37
  • 75