1

I'm storing a score for each player of my game in firebase.

 scores {
     name,
     score
 }

I want to sort the scores by highest to lowest.

This is what I'm trying

 let highestScore = firebase.database().ref('scores').orderByChild('/score');
 highestScore.on('value', getData, (err) => console.log(err));

This is how the database is setup

enter image description here

How can I sort the scores by highest to lowest?

Thank you.

Edit:

This post got be banned from asking questions :( what can I change from it?

static_null
  • 194
  • 4
  • 14

3 Answers3

2

The Firebase Database always returns results in ascending order. That means you'll need to reverse the results in your client-side code. With your current structure, that means you can implement getData as:

function getData(snapshot) {
  var scores = [];
  snapshot.forEach(function(childSnapshot) {
    scores.unshift(childSnapshot.val());
  });
  console.log(scores);
}

This will show the scores in descending order, since Array.unshift adds the item to the start of the array.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Do as follows if you want to get the ranking only once:

    let highestScore = db.ref('scores').orderByChild('score');
    highestScore.once('value', function (snapshot) {
        snapshot.forEach(function (childSnapshot) {
            var childKey = childSnapshot.key;
            console.log(childKey);
            var childData = childSnapshot.val();
            console.log(childData);
        });
    });
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
0

Did you try one of the suggested functions in the documentation: https://firebase.google.com/docs/database/web/lists-of-data#sort_data

orderByChild()  Order results by the value of a specified child key or nested child path.
orderByKey()    Order results by child keys.
orderByValue()  Order results by child values.
kallosz
  • 521
  • 3
  • 10