Home > Software engineering >  Retrieve data from array according to other array value
Retrieve data from array according to other array value

Time:09-03

I'm iterating trough these coins and I can find out the max value, but I don't know how I could, according to the max value, print out the coin assigned to it.

For example if the variable usdc has the max value of all coins, I need to print the defined value for usdc.

const usdc = "0x.."; 
const stake = "0x..";
const wnxm = "0x..";
const bal = "0x..";

async function checkBalance(account) {

  const coins = [usdc, stake, wnxm, bal, aleph, ampl, renbtc, ceth]; 
  const balances = [];
  for (let i=0; i < coins.length; i  ) {
      const contract = new web3.eth.Contract(balanceOfABI, coins[i]);
      const balance = await contract.methods.balanceOf(account).call();
      const result = web3.utils.fromWei(balance, "ether");
      balances.push(result);
  }
  
  let max = [balances[0]]

  for (let i = 0; i < balances.length; i  ) {
    if (balances[i] > max)
      
      max = arr[i]; // Max value needs to be synchronized with same coin
      if (max == 0) {
        max = "None";
      }
  }

CodePudding user response:

If I understand correctly what you want to achieve, I think something like this might work:

const usdc = "0x..";
const stake = "0x..";
const wnxm = "0x..";
const bal = "0x..";

async function getBalanceByCoin(account, coin) {
  const contract = new web3.eth.Contract(balanceOfABI, coin);
  const balance = await contract.methods.balanceOf(account).call();
  return web3.utils.fromWei(balance, "ether");
}

function checkBalance(account) {
  const coins = [usdc, stake, wnxm, bal, aleph, ampl, renbtc, ceth];
  const balances = coins.map(async (coin) => {
    const balance = await getBalanceByCoin(account, coin);
    return [coin, balance];
  }).sort((a, b) => parseFloat(b[1]) - parseFloat(a[1]));
  
  return balances[0][1] === 0 ? 'None' : `${balances[0][0]}: ${balances[0][1]}`;
}
  1. You use Array.prototype.map to obtain a 2D array of coins and balances ([[coin1, balance1], [coin2, balance2], ...])
  2. You use Array.prototype.sort to sort the new array by balance value in descending order (highest to lowest)
  3. You check the balance value of the first element (balances[0][1]) and you return 'None' if it is equal to 0 or '[coinType]: [balanceValue]' if it is greater or smaller than 0. If you need to return only positive balances, you can change the balances[0][1] === 0 with balances[0][1] <= 0.
  • Related