node.jsjsonchatbotvk

Node.js; list strings from JSON file in order


I have file users.json, which contain, among others, data like this:

[
  {
     "nick": "user123",
     "active24": 579
     ...
  }, {
     "nick": "nick",
     "active24": 259
     ...
  }
]

I want to make leaderboard, showing top 10 users nicks (from uknown max value of users), based on ther "active24" (from biggest to smallest). I can do it using array, but problem is that bot can't send it using vk-io (reason is not important, so i don't describe it much here, but please, do not save final input as array, but as variables or etc). I want output like:

Var_top1 = `${nick}: ${active24}`;
Var_top2 = `${nick}: ${active24}`;
Var_top3 = `${nick}: ${active24}`;
...
Var_top10 = `${nick}: ${active24}`;

P.S sorry for my bad English


Solution

  • do you want something like this?

    const data = [
      {
        nick: "user111",
        active24: 579
      },
      {
        nick: "nick222",
        active24: 0
      },
      {
        nick: "nick333",
        active24: 84
      },
      {
        nick: "nick444",
        active24: 9459
      }
    ];
    
      const sorted = data.sort((a, b) => b.active24 - a.active24);
      console.log(JSON.stringify(sorted)); 
      //[{"nick":"nick444","active24":9459},{"nick":"user111","active24":579},{"nick":"nick333","active24":84},{"nick":"nick222","active24":0}]
      const top1 = sorted[0];
      const top2 = sorted[1];
      const top3 = sorted[2];
      const top4 = sorted[3];