简体   繁体   中英

Firebase Leaderboard Sorting

I am trying to make a leaderboard with firebase, but I want it to sort based on points, for example

  1. 200 points
  2. 50 points
  3. 30 points

How would I do that?

This is my code:

var database = firebase.database();
var userRef = database.ref('countries');
userRef.orderByChild("points").once('value', function(snapshot) {
    var tr;
    var rank = 1;

    snapshot.forEach((countrySnapshot) => {
        tr = $('<tr/>');
        tr.append("<td>" + rank + "</td>");
        tr.append("<td>" + countrySnapshot.val().country.toLocaleString() + "</td>");
        tr.append("<td>" + countrySnapshot.val().points.toLocaleString() + "</td>");
        $('table').append(tr);
        rank = rank + 1;
});
})

This is how it looks like right now:

picture

Reverse the array before doing forEach . Looking at the documentation

Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.

var database = firebase.database();
var userRef = database.ref('countries');
userRef.orderByChild("points").once('value', function(snapshot) {
    var tr;
    var rank = 1;
    snapshot.reverse(); //add in this line
    snapshot.forEach((countrySnapshot) => {
        tr = $('<tr/>');
        tr.append("<td>" + rank + "</td>");
        tr.append("<td>" + countrySnapshot.val().country.toLocaleString() + "</td>");
        tr.append("<td>" + countrySnapshot.val().points.toLocaleString() + "</td>");
        $('table').append(tr);
        rank = rank + 1;
});
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM