Im using CoinCap API https://docs.coincap.io/ to grab current marketprices of the top 100 crypto currencies, then displaying the 5 coins that are down the most % (aka biggest losers). im making an array of 5 coins, iterating through each coin from the return from the api call, and comparing that coin to the 5 coins currently in the array.
if the coin is down more in the past 24h than the current coin in the array, replace it.
I was expecting the 5 biggest losers, instead i got 5 losers that I know are not the "biggest" losers (aka. there are other coins that are down more)
here is some of my code , the problem should be a simple logic issue that my brain is too worn down to notice, but let me know if i can provide any more info!
res.on("end", function ()
{
var body = Buffer.concat(chunks);
var data = JSON.parse(body.toString());
if (data && data.data)
{
var assets = data.data;
var losers = [];
for (var i = 0; i < assets.length; i++)
{
var asset = assets[i];
if (losers.length < 5)
{
losers.push(asset);
}
else
{
for (var j = 0; j < 5; j++)
{
if (asset.changePercent24Hr < losers[j].changePercent24Hr) {
losers[j] = asset;
break;
}
}
}
}
console.log("Top Losers:\n")
for (var i = 0; i < losers.length; i++) {
console.log( losers[i].name + " Price: " + formatter.format(losers[i].priceUsd) + " 24h: " + Number.parseFloat(losers[i].changePercent24Hr).toFixed(2) + "%");
}
}
else
{
console.log("No data found.");
}
});
solution - i simply added every coin to the array and then sorted it in descending order and popped 5 from it. probably less efficient this way but itll do for now, thanks to @derpirscher for the help