0

so I am trying to make a leaderboard of the players with more points, the object kinda looks like this:

let currency = {
    person1: {
        money: 1004,
        level: 20
    },
    person2: {
        money: 124,
        level: 3
    },
    person3: {
        money: 50144,
        level: 102
    }
} 

and what I want to do is it to create a leaderboard based on everyone's MONEY (not level) For example:

  1. person3 | 50144
  2. person1 | 1004
  3. person2 | 124

Any help will be appreciated since i have been stuck in this part.

2
  • 1
    Too bad it's not an array of objects, then it'd be a trivial property-based sort. (That's a hint :) Commented Jun 23, 2021 at 13:56
  • Does this answer your question? sort json object in javascript Commented Jun 23, 2021 at 13:56

1 Answer 1

1

Try iterating over your object using Object.entries, then you can filter the output array with Array.sort() and finally just Array.map() in order to get your desired format.

const currency = {
  person1: {
    money: 1004,
    level: 20,
  },
  person2: {
    money: 124,
    level: 3,
  },
  person3: {
    money: 50144,
    level: 102,
  },
};

const result = Object.entries(currency)
  .sort((a, b) => b[1].money - a[1].money)
  .map((p) => `${p[0]} | ${p[1].money}`);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.