nramirez nramirez - 5 months ago 86
Javascript Question

Better way to sum a property value in an array (Using Angularjs)

These days I started to work with Angularjs (Awesome :D) and I have found the next problem:

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

I decided to use @gruff-bunny suggestion, so I avoid prototyping native object (Array)

I just did a little modification to his answer validating the array and the value to sum aren't null, this is my final implementation:

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

Answer

Since it is an array you could add a function to the Array prototype.

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

Array.prototype.sum = function (prop) {
    var total = 0
    for ( var i = 0, _len = this.length; i < _len; i++ ) {
        total += this[i][prop]
    }
    return total
}

console.log(traveler.sum("Amount"))

The Fiddle: http://jsfiddle.net/9BAmj/

Comments