Hi I’m working on a game application. The schema of the game database looks like this
JavaScript
x
8
1
[
2
{
3
UserName,
4
UserImage,
5
UserScore
6
}
7
]
8
Here is an example snippet. I would like to sort the json array based on the score and extract the top 10(if any).
JavaScript
1
26
26
1
[{
2
name: "user1",
3
image: "image",
4
score: 10
5
},
6
{
7
name: "user2",
8
image: "image",
9
score: 167
10
},
11
{
12
name: "user3",
13
image: "image",
14
score: 1
15
},
16
{
17
name: "user4",
18
image: "image",
19
score: 102
20
},
21
{
22
name: "user5",
23
image: "image",
24
score: 12
25
}
26
]
I’m having trouble sorting this array based on the userScore so that I could display the top 10 on the leaderboards. Any help would be greatly appreciated.
Advertisement
Answer
try it for sort by number:
JavaScript
1
7
1
const sortNum = (arr) => {
2
arr.sort(function (a, b) {
3
return a - b;
4
});
5
return arr;
6
};
7
in your case:
JavaScript
1
7
1
const sortNum = (arr) => {
2
arr.sort(function (a, b) {
3
return a.score - b.score;
4
});
5
return arr;
6
};
7