Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum json array

How can I to sum elements of a JSON array like this, using jQuery:

"taxes": [ 
    { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0, "taxCode": "YRI" },
    { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0, "taxCode": "YRI" },
    { "amount": 10, "currencyCode": "USD", "decimalPlaces": 0, "taxCode": "YRI" }
]

The result should be:

totalTaxes = 60

like image 681
Louis Avatar asked Apr 19 '12 03:04

Louis


1 Answers

If you really must use jQuery, you can do this:

var totalTaxes = 0;

$.each(taxes, function () {
    totalTaxes += this.amount;
});

Or you can use the ES5 reduce function, in browsers that support it:

totalTaxes = taxes.reduce(function (sum, tax) {
    return sum + tax.amount;
}, 0);

Or simply use a for loop like in @epascarello's answer...

like image 75
Ates Goral Avatar answered Oct 22 '22 05:10

Ates Goral