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

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

3 Answers3

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)
Tom O.
  • 5,730
  • 2
  • 21
  • 35
Phil
  • 10,948
  • 17
  • 69
  • 101
  • 2
    You could even eliminate the map in the chain by doing: `.reduce((acc, curr) => acc + parseFloat(curr.billed), 0)` – Devon Norris Mar 20 '20 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}`);
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • Based on this answer, why would I use `Number`? https://stackoverflow.com/questions/12227594/which-is-better-numberx-or-parsefloatx – Phil Mar 20 '20 at 22:41
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.

moficodes
  • 781
  • 1
  • 6
  • 21