In AngularJS, calculating the sum of values in an array can often be performed using loops. However, to facilitate code reusability, consider a more efficient approach.
Instead of using explicit loops, leverage the reduce method to calculate the sum. Here's an optimized function:
$scope.sum = function(items, prop) { return items.reduce( function(accumulator, currentItem) { return accumulator + currentItem[prop]; }, 0 // Optional starting value ); };
Now, you can reuse this function for any array with a custom property name:
// For the $scope.traveler array $scope.travelerTotal = $scope.sum($scope.traveler, 'Amount'); // For a different array, e.g. $scope.expenses $scope.expensesTotal = $scope.sum($scope.expenses, 'Cost');
This approach offers several advantages:
The above is the detailed content of How Can I Efficiently Sum Array Property Values in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!