Sum each attributes value from api response javascript -
you need kind of loop. 1 solution use foreach
data
variable array received api response.
var sum=0; var data=[{points_earned:"2"},{points_earned:4}] data.foreach(function(elem){ sum+=number(elem.points_earned); }); console.log(sum); var sumusingreduce=0; var total = data.reduce(function(sum, value) { return sumusingreduce += number(value.points_earned) }, 0); console.log(sumusingreduce);
var sum=0; data.foreach(function(elem){ sum+=elem.points_earned; });
others suggested using reduce:
the reduce() method applies function against accumulator , each element in array (from left right) reduce single value.
example:
var total = [0, 1, 2, 3].reduce(function(sum, value) { return sum + value; }, 0);
Comments
Post a Comment