Reuben Gomes Reuben Gomes - 4 months ago 16
Javascript Question

Adding values contained in an array of objects

How would I go about adding all the values within the object?

For example

amoutpay": ["4222","1000"]
would give me
5222


This is my object:

{
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
}


What I want is to add the values to variables. Would I use split?

var a =
var b =
var c =

Answer

You can use Array.prototype.reduce() as shown below:

var obj = {
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
},
    
    a = obj.amoutpay.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    }),
    b = obj.amtpending.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    }),
    c = obj.totalcost.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    });

console.log( a, b, c );

Comments