0

I am trying to get a kind of "leaderboard" from a list of numbers. I was thinking of making an array with all the numbers like this

var array = [];
for (a = 0; a < Object.keys(wallets.data).length; a++) { //var wallets = a JSON (parsed) response code from an API.
    if (wallets.data[a].balance.amount > 0) {
        array.push(wallets.data[a].balance.amount)
    }
}
//Add some magic code here that sorts the array into descending numbers

This is a great option, however I need some other values to come with the numbers (one string). That's why I figured JSON would be a better option than an array. I just have no idea how I would implement this.

I would like to get a json like this:

[
    [
     "ETH":
        {
         "balance":315
        }
    ],
    [
     "BTC":
        {
         "balance":654
        }
    ],
    [
     "LTC":
        {
         "balance":20
        }
    ]
]

And then afterwards being able to call them sorted descending by balance something like this:

var jsonarray[0].balance = Highest number (654)
var jsonarray[1].balance = Second highest number (315)
var jsonarray[2].balance = Third highest number (20)

If any of you could help me out or point me in the right direction I would appreciate it greatly.

PS: I need this to happen in RAW JS without any html or libraries.

WoJo
  • 500
  • 1
  • 3
  • 20

3 Answers3

1

You should sort the objects before making them a JSON. You can write your own function or use a lambda. See this [https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value]

Nico Godoy
  • 27
  • 1
  • 5
0

Since you are dealing with cryptocurrency you can use the currency-code as a unique identifier.

Instead of an array, you can define an object with the currency as properties like this:

const coins = {
     ETH: [300, 200, 500],
     BTC: [20000, 15000, 17000]
}

then you can access each one and use Math.max or Math.min to grab the highest / lowest value of that hashmap. E.G. Math.max(coins.BTC)

And if you need to iterate over the coins you have Object.keys:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Salmin Skenderovic
  • 1,750
  • 9
  • 22
0

Thank you all for your answer. I ended up using something like:

leaderboard = []
for (a = 0; a < Object.keys(wallets.data).length; a++) {
    if (wallets.data[a].balance.amount > 0) {
        leaderboard.push({"currency":wallets.data[a].balance.currency, "price":accprice}) //accprice = variable which contains the value of the userhold coins of the current coin in EUR
    }
}
console.log(leaderboard.sort(sort_by('price', true, parseInt)));
WoJo
  • 500
  • 1
  • 3
  • 20