Selvi P Selvi P - 23 days ago 8
Javascript Question

How to sum property values of an object?

I want to sum the property values of

PieData
. My expected output is
25515512+916952499 = 942468011


var PieData = [
{
value: 25515512,
color: "#00a65a",
highlight: "#00a65a",
label: "Received Fund"
},
{
value: 916952499,
color: "#f56954",
highlight: "#f56954",
label: "Pending Fund"
}
];


Here is the script i have tried: It prints undefined value.

var total_value='';
for(var i=0;i<PieData.length;i++){
$.each(PieData[i], function (index, val) {
total_value += val.value;
});
}
alert(total_value);

Answer

You could use the native method Array#reduce for it.

var PieData = [{ value: 25515512, color: "#00a65a", highlight: "#00a65a", label: "Received Fund" }, { value: 916952499, color: "#f56954", highlight: "#f56954", label: "Pending Fund" }],
    sum = PieData.reduce(function (s, a) {
        return s + a.value;
    }, 0);

console.log(sum);

ES6

var PieData = [{ value: 25515512, color: "#00a65a", highlight: "#00a65a", label: "Received Fund" }, { value: 916952499, color: "#f56954", highlight: "#f56954", label: "Pending Fund" }],
    sum = PieData.reduce((s, a) => s + a.value, 0);

console.log(sum);

Comments