Home >Web Front-end >JS Tutorial >How Can I Efficiently Sum the Values of a Specific Property Across Multiple JavaScript Arrays?
Efficient Array Value Summation
This question seeks an efficient solution for calculating the total sum of a specific property across multiple arrays.
Problem Statement
Given an array of objects, each containing a "description" and an "Amount" property, the original approach involved iterating through the array and incrementally adding the "Amount" values:
$scope.totalAmount = function(){ var total = 0; for (var i = 0; i < $scope.traveler.length; i++) { total = total + $scope.traveler[i].Amount; } return total; }
Equivalent Method for Arbitrary Properties
The desired solution would allow for summing of arbitrary property values, expressed as:
$scope.traveler.Sum({ Amount }); $scope.someArray.Sum({ someProperty });
Optimized Solution
The proposed solution leverages the array.reduce method to achieve this goal:
$scope.sum = function(items, prop){ return items.reduce( function(a, b){ return a + b[prop]; }, 0); }; $scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');
Advantages
The above is the detailed content of How Can I Efficiently Sum the Values of a Specific Property Across Multiple JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!