Home >Web Front-end >JS Tutorial >How Can I Efficiently Sum Property Values Across Multiple Arrays in JavaScript?

How Can I Efficiently Sum Property Values Across Multiple Arrays in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 19:48:11725browse

How Can I Efficiently Sum Property Values Across Multiple Arrays in JavaScript?

Efficiently Summing Property Values in Arrays

To calculate the total amount in an array, you typically employ a straightforward loop as seen in the given example:

for (var i = 0; i < $scope.traveler.length; i++) {
  total = total + $scope.traveler[i].Amount;
}

This approach can become tedious when dealing with multiple arrays and various property names. The ideal solution would allow concise summation using a standardized method.

Enter the reduce function:

The reduce function applies a reducer function to each element of an array, accumulating the results into a single value. In this case, we define a reducer function that adds the target property value to the running total:

$scope.sum = function(items, prop){
  return items.reduce( function(a, b){
    return a + b[prop];
  }, 0);
};

By utilizing reduce, you can effortlessly calculate the total for any array and property:

$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');

This generalized approach provides flexibility and efficiency for summing property values in diverse arrays.

The above is the detailed content of How Can I Efficiently Sum Property Values Across Multiple Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn