Reputation: 89
So i have this array of objects that looks like this:
let budgetData = [{title: "Monthly Income", amount: "2500"}, {title:
"rent", amount: "1000"},{title: "car", amount: "200"};
I am trying to some math like this:
2500 - 1000 - 200 = whatever this comes out too. You can continue to add amounts to this array until you have added your monthly expenses.
When you run this the first time with only two values the amount is what you would expect (ie. 2 - 1 = 1).
However add anymore than two amounts to the array it only subtracts whatever the last value is from the first value.(ie. 5 - 2 - 1 = 4).
let amount = [];
for (let i = 1; i < budgetData.length; i++){ amount =
budgetData[0].amount - budgetData[i].amount;
Console.log(amount) === 2300
So this code with the above info the answer comes out to: 2300 when I am expecting it to say 1300.
Where am I going wrong with this, also, is there some built in math function that will do what I am trying to do?
Upvotes: 2
Views: 3238
Reputation: 138417
Alternatively you could reduce the array:
const total = budgetData.reduce((previous, current) => (previous.amount || previous) - current.amount);
If your budget objects implement a valueOf method, like this:
class Budget {
constructor(settings){
Object.assign(this, settings);
}
valueOf(){ return this.amount;}
}
budgetData = budgetData.map(el => new Budget(el));
It gets even more beautiful:
const total = budgetData.reduce((a,b) => a-b);
Upvotes: 1
Reputation: 85102
Each time through the loop you're throwing away what you calculated before, and overwriting amount
with a new calculation. So what you end up at the very end is just subtracting the very last number from the first number.
Instead, you need to keep a running tally. Something like this:
let budgetData = [
{title: "Monthly Income", amount: "2500"},
{title: "rent", amount: "1000"},
{title: "car", amount: "200"}
];
let amount = budgetData[0].amount;
for (let i = 1; i < budgetData.length; i++){
amount = amount - budgetData[i].amount;
}
console.log(amount);
Upvotes: 1