1

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

2
  • What is 0l please?CommentedMar 20, 2020 at 21:00
  • What is payments and what is amountPaidCents?CommentedMar 20, 2020 at 21:04

3 Answers 3

3

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) 
1
  • 2
    You could even eliminate the map in the chain by doing: .reduce((acc, curr) => acc + parseFloat(curr.billed), 0)CommentedMar 20, 2020 at 21:00
2

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}`);

1
1

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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.