-2

Hi I'm working on a game application. The schema of the game database looks like this

[
  {
    UserName,
    UserImage,
    UserScore
  }
]

Here is an example snippet. I would like to sort the json array based on the score and extract the top 10(if any).

[{
    name: "user1",
    image: "image",
    score: 10
  },
  {
    name: "user2",
    image: "image",
    score: 167
  },
  {
    name: "user3",
    image: "image",
    score: 1
  },
  {
    name: "user4",
    image: "image",
    score: 102
  },
  {
    name: "user5",
    image: "image",
    score: 12
  }
]

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.

A47
  • 11
  • 2
  • 2
    Welcome. Please see [How to ask](https://stackoverflow.com/help/how-to-ask) and take the [tour](https://stackoverflow.com/tour). You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example) – DecPK Dec 05 '21 at 08:28
  • 1
    Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – pilchard Dec 05 '21 at 11:05

1 Answers1

0

try it for sort by number:

 const sortNum = (arr) => {
    arr.sort(function (a, b) {
      return a - b;
    });
    return arr;
  };

in your case:

  const sortNum = (arr) => {
        arr.sort(function (a, b) {
          return a.score - b.score;
        });
        return arr;
      };
foad abdollahi
  • 1,733
  • 14
  • 32