Sum values inside of array with javascript

213
January 11, 2018, at 01:16 AM

I'm getting info from an api, and what I want to do is sum the values inside of it. Let's say that the next code:

function totalPesos(){
    $http.get('/api/valueForTest')
    .then(function(data){
        $scope.resumePesos = data.data.Response;
        //console.log($scope.resumePesos);
}

Get the next answer:

[{Id: 60, Name: Chuck, Quantity: 300},
{Id: 61, Name: Arthur, Quantity: 199},
{Id: 62, Name: John, Quantity: 450}]

What I want to do is sum the Quantity. How can I do that? I've tried with:

$scope.resumePesos.reduce(function(a,b){return a + b; });

But the answer was [object Object]

Answer 1

I would write it like this:

$scope.resumePesos.reduce((acc, x) => acc + x.Quantity, 0);

Remember that the 1st argument to the function passed to reduce is the accumulator, and the 2nd is each value you are iterating over, which in this case will be each object. Therefore you need to access the Quantity property of each object. Then you need to pass the initial value of the accumulator as the 2nd argument to reduce itself. Which in this case will be 0, since we want just a number as the result

Answer 2

Try the following with pure JS:

var data = [{Id: 60, Name: 'Chuck', Quantity: 300}, 
{Id: 61, Name: 'Arthur', Quantity: 199}, 
{Id: 62, Name: 'John', Quantity: 450}] 
var sum = data.reduce(function(a, b){ 
  a += b['Quantity']; 
  return a; 
},0) 
console.log(sum);

Answer 3

You should try this instead:

$scope.resumePesos.reduce((a,b) => {return a + b.Quantity}, 0); // Note: 0 at the end
Answer 4

You are doing two things wrong - you haven't set an initial value to the reduce function and you are summing object instead of its numerical property (.Quantity).

 var sum = $scope.resumePesos.reduce(function(acummulated, rp) {
  return accumulated + rp.Quantity; 
 }, 0);
Answer 5


Just Use

$scope.sum = $scope.resumePesos.reduce(function(a,b){return a + b.Quantity; }, 0);
Answer 6

You can use lodash and it will be useful if you want some other functions on lodash.

You can do

_.sumBy($scope.resumePesos, 'Quantity');

var data = [ 
  {Id: 60, Name: 'Chuck', Quantity: 300}, 
  {Id: 61, Name: 'Arthur', Quantity: 199}, 
  {Id: 62, Name: 'John', Quantity: 450} 
] 
   
console.log(_.sumBy(data, 'Quantity')); 
   
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer 7

Thanx to all, i've tried with all your comments, and worked fine!

READ ALSO