const bankAccounts = [
{
id: 1,
name: "Susan",
balance: 100.32,
deposits: [150, 30, 221],
withdrawals: [110, 70.68, 120],
},
{ id: 2, name: "Morgan", balance: 1100.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: 0.0 },
{ id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];
function getClientsWithWrongBalance(bankAccounts) {
const newArray = [];
for (let obj of bankAccounts) {
let sum = 0;
if (obj.deposits) {
for (let numDep of obj.deposits) {
sum += numDep;
}
}
if (obj.withdrawls) {
for (let numWith of obj.withdrawls) {
sum += numWith;
}
}
}
return newArray;
}
I have five bank accounts (objects) in the bankAccounts (array) variable. What I am trying to do is use for loops only to iterate through each account (object) and add up all the deposits elements and all the withdrawals elements, then I need to subtract the withdrawal from the deposit and see if it equals the balance key value pair of the accounts (object). I get stuck with my code when I can only add all of the elements of the deposits and withdrawals array’s up. I do not know how to proceed. I have just messed around and tried different blocks of code. But I cannot figure out what to do.
>Solution :
function getClientsWithWrongBalance(bankAccounts) {
const newArray = [];
for (let obj of bankAccounts) {
let dsum = 0;
let wsum = 0;
if (obj.deposits) {
for (let numDep of obj.deposits) {
dsum += numDep;
}
}
if (obj.withdrawls) {
for (let numWith of obj.withdrawls) {
wsum += numWith;
}
}
if (obj.balance != (dsum - wsum)) {
newArray.push(obj);
}
}
return newArray;
}
Total deposits and withdrawals separately, compare to balance, and save any differences in the array returned.