Home > Web Front-end > JS Tutorial > How Can I Efficiently Sum Array Property Values in AngularJS?

How Can I Efficiently Sum Array Property Values in AngularJS?

Mary-Kate Olsen
Release: 2024-12-08 15:53:11
Original
766 people have browsed it

How Can I Efficiently Sum Array Property Values in AngularJS?

Enhanced Method for Summing Array Property Values

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.

Optimized Summing Function

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

Usage for Different Property Names

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

Benefits

This approach offers several advantages:

  • Improved code readability: Eliminates explicit loops, making the code easier to understand.
  • Enhanced code reusability: The function can be reused for any array with a custom property name.
  • Increased efficiency: The reduce method is optimized for summing operations on arrays.

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!

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