I could not update balance that inside array

I have a table like in the picture


I want to update my balance dynamically according to debit,credit and previous balance. I have created function in ternary operator like this.

 
      entries: entries.map((item,index,array) => ({ ...item, balance:
          index===0?item.credit:(
            
              item.credit===undefined?(array[index-1].balance-item.debit):(array[index-1].balance+item.credit)
            
          )
        
        
         })),

But it doesnt work, only my first balance is updated. What I am doing wrong?

item in (item, index, array) is one row in the table, so I don’t think …item, balance is going to achieve what you want.

You can use reduce and carry an array of balances as it’s accumulator. When you’re done, you have an array of balances like [100.00, 96.86, 93, 72, 95.71, …]. Then you can retrace the entries array and update the balance field of corresponding rows.

Or you can use reduce to carry an array of (new) rows as it’s accumulator. At each iteration, the most recent balance is the one from the last row in the accumulator. Update this row’s balance, add this new updated row to the accumulator.

Does it make sense?

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.