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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With