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
Release: 2024-12-10 19:48:11
Original
772 people have browsed it

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;
}
Copy after login

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);
};
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template