Skip to content
Advertisement

Sorting a array based on a specific value

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.

Advertisement

Answer

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;
      };
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement