firebase sort reverse order

后端 未结 3 1526
深忆病人
深忆病人 2021-01-19 07:19

var playersRef = firebase.database().ref(\"team_mapping/\");


playersRef.orderByChild(\"score\").limitToFirst(7).on(\"child_added\", function(data) {
}
         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 08:00

    You can limit to the last 7 which will give you the highest scores since the query is in ascending order. Then all you have to do is reverse the last 7 you get for them to be in descending order.

    var playersRef = firebase.database().ref("team_mapping/");
    var playersData = [];
    var pageCursor;
    
    playersRef.orderByChild("score").limitToLast(7).on("child_added", function(data) {
        playersData = [data] + playersData;
    }
    

    UPDATE

    Here is an example of how you could paginate by score.

    const query = firebase.database().ref("team_mappings").orderByChild('score');
    
    var snapshots = [];
    
    function reversedChildren(snapshot) {
        var children = [];
        snapshot.forEach(function (child) { children.unshift(child); });
        return children;
    }
    
    function addPlayerToLeaderBoard(snapshot) {
        var key = snapshot.key;
        var place = snapshots.indexOf(snapshot) + 1;
        var score = snapshot.child('score').val();
        $('#leaderboard').append(`
  • ${key}: ${score}
  • `); } function parsePage(snapshot) { var children = reversedChildren(snapshot); children.forEach(function (child) { players.push(child); addPlayerToLeaderBoard(child); }); pageCursor = children[children.length - 1]; } function reloadPlayers() { players = []; pageCursor = null; query.limitToLast(5).once('value').then(parsePage); } function loadMorePlayers() { query.endAt(pageCursor).limitToLast(5).once('value').then(parsePage); } reloadPlayers(); $('#reload').on('click', reloadPlayers); $('#load_more').on('click', loadMorePlayers);

提交回复
热议问题