Reputation: 5660
I have an array json object called payment
[ { billed : "100", owed: "50" }, { billed : "200", owed: "100" }]
I want to sum up "billed" field and net answer should be 300. I tried the following:
let paidPaymentCents = 0;
for (let payment in payments) {
paidPaymentCents += payments[payment].billed;
}
Is there any better way using reduce : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Upvotes: 1
Views: 75
Reputation: 11175
JavaScript's reduce() would be the method for this. Once the JSON
is parsed and you have an array or objects:
let testAry = [{ billed : "100", owed: "50" }, { billed : "200", owed: "100" }],
amt = testAry
// 1. isolate and parse
.map(item => parseFloat(item.billed))
// 2. add up all billed
.reduce((a, b) => a + b, 0);
console.log(amt)
Depending on the consistency of the data, you might want to use Number
instead of parseFloat
. More here: parseFloat vs Number
You can make it smaller (thanks @Devon):
.reduce((acc, curr) => acc + parseFloat(curr.billed), 0)
Upvotes: 3
Reputation: 5941
You could do this very easily using Array.prototype.reduce
. Within the reduce, you can treat each element.billed
as a number instance by wrapping it with Number
. You would start with 0
as your accumulator and add each element.billed
to get the total. Here is an example:
const data = [{
billed: "100",
owed: "50"
}, {
billed: "200",
owed: "100"
}];
const total = data.reduce((runningTotal, element) => {
runningTotal += Number(element.billed);
return runningTotal;
}, 0);
console.log(`Total billed amount is ${total}`);
Upvotes: 2
Reputation: 869
Each of the payment object in the loop has the structure { billed : "100", owed: "50" }
So you can do
let payments = [ { billed : "100", owed: "50" }, { billed : "200", owed: "100" }]
let paidPaymentCents = 0;
for (var i = 0;i < payments.length; i++) {
paidPaymentCents += Number(payments[i].billed);
}
And you will have the paidPaymentCents
will have the total.
Upvotes: 1