Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Sum of an Array

I have an array in AngularJS, which I'm getting from a WCF Service. I can achieve the sum of the array using a function like below. reference: Calculating sum of repeated elements in AngularJS ng-repeat

$scope.getTotal = function(){
    var total = 0;
    for(var i = 0; i < $scope.cart.products.length; i++){
        var product = $scope.cart.products[i];
        total += (product.price);
    }
    return total;
}

But, is there any way to achieve this without filter? just like $scope.cart.products.price.Sum()? I already used so many filters and functions in my code, want to reduce its count.

like image 476
Manoj Kumar Avatar asked Apr 29 '16 11:04

Manoj Kumar


Video Answer


1 Answers

Use reduce.

$scope.cart.products.reduce(function(acc,current){
    return acc + current.price;
},0);

Or in ES6:

$scope.cart.products.reduce((acc,current) => acc + current.price, 0);

Check here for MDN docs on reduce.

like image 122
Luka Jacobowitz Avatar answered Sep 28 '22 05:09

Luka Jacobowitz