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

How Can I Efficiently Sum the Values of a Specific Property Across Multiple JavaScript Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 19:34:10985browse

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

  • Reusability: This solution can be reused for any array by passing the appropriate arguments to the sum function.
  • Conciseness: It encapsulates the summing logic in a single method, eliminating the need for explicit iteration loops.
  • Improved Performance: Reduce provides inherent performance optimizations for array processing.

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!

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