0

I'm trying to create a scoreboard with a username and score that is sorted in numeric order. At the moment the scoreboard is sorted based on the username.

The score list should be sorted based on the score value but I'm not sure how. Do I have to change the data type somehow to be able to sort?

Javascript (data is from firebase)

const scorelist = document.querySelector("#scorelist")

function gotData(data) {
    var scores = data.val();
    var keys = Object.keys(scores);

    console.log(keys)

    for (var i = 0; i < keys.length; i++) {
      var k = keys[i];
      var score = scores[k].score;
      const newListItem = document.createElement("ul", score);
      newListItem.textContent = k + " - " + score;
      scorelist.appendChild(newListItem);
    }
    console.log()
  }

function errData(err) {
    console.log('Error!');
    console.log(err)
}

HTML code:

<p>
   <ul id ="scorelist">
   </ul>
</p>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    `
      ` is not a list item (`
    • `). You're generating invalid markup right now.
    – Andreas Aug 13 '21 at 11:32
  • 1
    And _"Thank you!"_ is not code and should not be there in the first place. – Andreas Aug 13 '21 at 11:33
  • 1
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) and [Question Checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Please search thoroughly before posting. – T.J. Crowder Aug 13 '21 at 11:35
  • 2
    In this specific case, you probably want to [sort](https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) the `keys` before you create the elements. But if you ever do need to actually sort DOM elements, see [the answers here](https://stackoverflow.com/questions/24342242/javascript-to-sort-dom-elements-by-some-comparator-without-jquery). – T.J. Crowder Aug 13 '21 at 11:35

0 Answers0