Sum each attributes value from api response javascript -


i want sum similar attributes api response.

enter image description here

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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -