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

8

2 Answers

Working with JSON 101

var foo = {
        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"}
        ]
    },
    total = 0,  //set a variable that holds our total
    taxes = foo.taxes,  //reference the element in the "JSON" aka object literal we want
    i;
for (i = 0; i < taxes.length; i++) {  //loop through the array
    total += taxes[i].amount;  //Do the math!
}
console.log(total);  //display the result
2

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest