5

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.

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or $scope.cart.products.reduce(function(sum,current){ return sum + current.price; }, 0);
The acc (or previous value) is the value previously returned in the last invocation of the callback, or initialValue, if supplied. On the second loop it will be number without price property

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.