javascriptfor-loop

using only for loops find the bank accout with the lowest sum but not zero ( if no account balance is above 0 return an empty array


I'm working on an exercise that only allows us to use for loops for iterating. the question I'm working on is asking to return the bank account balance that has the lowest balance , so the minimum of all the accounts. and in case there are no accounts that have a balance above 0 return an empty array.

this is what I have so far I can't see what I've skipped, or overlooked any tips would be greatly appreciated!

//expected output 
min = { id: 2, name: "Morgan", balance: 3.0, deposits: [1100] }

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 3.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 10.0 },
  { id: 5, name: "Phil", balance: 18.0, deposits: [100, 18], withdrawals: [100] },
];


function itsSomething(array){
  // Your code goes here...
  let min = 0;
  let minMin =[];
  for (let i = 0; i < array.length; i++){
   if (array[0].balance > array[i].balance && array[i].balance >0 ){
     min = array[i]
   }else if ( array[i].balance > array[0].balance && array[0].balance > 0 ){
     min = array[0]
   }else if ( array[i].balance && array[0].balance < 0 ){
     min = []
   }
  } 
   return min
   
 }

console.log(itsSomething(bankAccounts))


Solution

  • On each iteration, if the current element has a positive balance, compare it with the previous lowest balance. If the current balance is lower (or there was no previous account), then update the result.

    const bankAccounts=[{id:1,name:"Susan",balance:100.32,deposits:[150,30,221],withdrawals:[110,70.68,120]},{id:2,name:"Morgan",balance:3,deposits:[1100]},{id:3,name:"Joshua",balance:18456.57,deposits:[4e3,5e3,6e3,9200,256.57],withdrawals:[1500,1400,1500,1500]},{id:4,name:"Candy",balance:10},{id:5,name:"Phil",balance:18,deposits:[100,18],withdrawals:[100]}];
    
    function itsSomething(array){
      let res = [];
      for (let i = 0; i < array.length; i++)
        if (array[i].balance > 0 && !(res.balance < array[i].balance))
          res = array[i];
      return res;
    }
    
    console.log(itsSomething(bankAccounts))