简体   繁体   中英

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]

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

你应该试试这个:

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

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


只是使用

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

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

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> 

对所有人来说,我已经尝试了所有的评论,并且工作得很好!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM