Better way to sum a property value in an array

nramirez picture nramirez · Apr 23, 2014 · Viewed 243.4k times · Source

I have something like this:

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

Now to have a total Amount of this array I'm doing something like this:

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

It's easy when is only one array, but I have others arrays with a different property name that I would like to sum.

I would be happier If I could do something like this:

$scope.traveler.Sum({ Amount });

But I don't know how to go through this in a way that I could reuse it in the future like this:

$scope.someArray.Sum({ someProperty });

Answer

Gruff Bunny picture Gruff Bunny · Apr 23, 2014

I know that this question has an accepted answer but I thought I'd chip in with an alternative which uses array.reduce, seeing that summing an array is the canonical example for reduce:

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

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

Fiddle