8
"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]

I want to sum "pendingAmount" field. It should be return like pendingAmount: 61050

Asef Hossini
  • 655
  • 8
  • 11
Avijit Dutta
  • 3,651
  • 3
  • 13
  • 16

5 Answers5

14

You can use Array#map and then Array#reduce to flatten your object and then sum the result of the map :

bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);

here's a snippet :

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
var res = bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
console.log(res)

Hope it helps,

Best regards,

boehm_s
  • 5,254
  • 4
  • 30
  • 44
6

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
        
        
      var result = bills.reduce(function(_this, val) {
          return _this + val.pendingAmount
      }, 0);

    console.log(result)
    //61050 answer
Sujith S
  • 555
  • 5
  • 8
0

You could use the following snippet:

var sum = JSON.parse(bills).reduce(function(acc, val){
  return acc.pendingAmount + val.pendingAmount;
}, {pendingAmount: 0});

it uses the array.prototype.reduce() function on the parsed JSON. The second argument of the reduce is the initial value passed to the reduce function

Fabian
  • 531
  • 4
  • 11
0

A one-liner with some ES2015 destructuring:

json.bills.reduce(({pendingAmount: a}, {pendingAmount: b})=> a+b)
gunn
  • 8,999
  • 2
  • 24
  • 24
-1

Use this:

let sum, billsPOJO;

billsPOJO = YOURJSON.bills;

sum = 0;

for (let i = 0; billsPOJO.length; i++) {
 sum += billsPOJO[i].pendingAmount; 
}
F.bernal
  • 2,594
  • 2
  • 22
  • 27
  • Its a whole lot of work to do. Why do this if JS mainly ES6 is giving you shorthand & oneliner way to achieve this! – TalESid Jun 20 '20 at 11:21