javascript - 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
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?
解决方案
Firebase 数据库始终按升序返回结果。这意味着您需要在客户端代码中反转结果。使用您当前的结构,这意味着您可以实现getData
为:
function getData(snapshot) {
var scores = [];
snapshot.forEach(function(childSnapshot) {
scores.unshift(childSnapshot.val());
});
console.log(scores);
}
这将按降序显示分数,因为Array.unshift
将项目添加到数组的开头。