Chuck Villavicencio
Chuck Villavicencio

Reputation: 393

Sum values inside of array with javascript

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]

Upvotes: 2

Views: 114

Answers (7)

Chuck Villavicencio
Chuck Villavicencio

Reputation: 393

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

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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);

Upvotes: 2

arunmmanoharan
arunmmanoharan

Reputation: 2675

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>

Upvotes: 1

Jackson Lenhart
Jackson Lenhart

Reputation: 650

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

Upvotes: 1

Muhammed Anees
Muhammed Anees

Reputation: 1850


Just Use

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

Upvotes: 1

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

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);

Upvotes: 1

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

You should try this instead:

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

Upvotes: 1

Related Questions