"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Sum Array Properties in AngularJS?

How Can I Efficiently Sum Array Properties in AngularJS?

Published on 2024-12-20
Browse:515

How Can I Efficiently Sum Array Properties in AngularJS?

Advanced Array Summation in AngularJS

In AngularJS, summing array properties can be a common task. A basic approach involves iterating through the array and accumulating the property values. However, this method becomes tedious when faced with multiple arrays and varying property names.

To address this, a more flexible and reusable solution is desired, one that allows for convenient summation of any array property. This can be achieved using the reduce() method, which provides a powerful way to aggregate array values.

Consider the following example:

$scope.traveler = [
    { description: 'Senior', Amount: 50},
    { description: 'Senior', Amount: 50},
    { description: 'Adult', Amount: 75},
    { description: 'Child', Amount: 35},
    { description: 'Infant', Amount: 25 },
];

To sum the 'Amount' property of the traveler array using reduce(), we can write a method as follows:

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

In this method, we use the reduce() method with a callback function that accepts two arguments: the accumulated value (a) and the current element (b) of the array. Within the callback, we access the property we want to sum (prop) and add it to the accumulated value.

To apply this method to our traveler array, we can do the following:

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

Using this approach, we can easily sum property values of any array in our AngularJS application. By defining a reusable method, we avoid redundant code and ensure consistency in our summation calculations.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3