首页 > 解决方案 > sorting numbers with firebase

问题描述

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?

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-firestore

解决方案


Firebase 数据库始终按升序返回结果。这意味着您需要在客户端代码中反转结果。使用您当前的结构,这意味着您可以实现getData为:

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

这将按降序显示分数,因为Array.unshift将项目添加到数组的开头。


推荐阅读