I want to show the current amount available in the wallet after a transaction, in the transactions list for that particular transaction.
Here is my code
let Transactions = [{title:'txn1',amount:100,type:'credit',date:'01-01-2021'},{title:'txn1',amount:150,type:'credit',date:'01-02-2021'},{title:'txn1',amount:60,type:'debit',date:'01-03-2021'},{title:'txn1',amount:50,type:'debit',date:'01-04-2021'}];
let totalCredit = Transactions.reduce((amount,txn)=>{ return (txn.type === 'credit' && (parseFloat(amount) + parseFloat(txn.amount)) || amount) },0);
let totalDebit = Transactions.reduce((amount,txn)=>{ return (txn.type === 'debit' && (parseFloat(amount) + parseFloat(txn.amount)) || amount) },0);
let currentBalance = totalCredit - totalDebit;
let txncards=[];
let txn_cb = 0;
Transactions = Transactions.sort((a,b)=>{
a.date = new Date(a.date), b.date = new Date(b.date)
if(a.date<b.date) return 1;
if(a.date>b.date) return -1;
return 0;
})
Transactions.forEach((txn)=>{
txn_cb = txn_cb + txn.amount;
txn.cb = txn_cb;
txncards.push(makecard(txn));
})
$('.card-body').html(txncards);
const makecard = (txn) =>{
//this returns HTML ul li list jQuery Object filled with details provided by txn object
}
Result
As you can see the order of the list is not as expected by sorting by date in descending order; And the available balance is not correct in li. Txn 1 should be at the bottom and the available balance should be 100 Txn 2 should be in the middle and the available balance should be 200 Txn 3 should be at the top and the available balance should be 150
so where am I doing wrong? please ignore minor typos