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 get the total number of this array, I am 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; }
This is easy when there is only one array, but I have other arrays with a different property name that I would like to summarize.
I would be happy if I could do something like this:
$scope.traveler.Sum({ Amount });
But I donโt know how to get through this so that I can use it in the future, like this:
$scope.someArray.Sum({ someProperty });
Answer
I decided to use the @ gruff-bunny sentence to avoid prototyping the native object (Array)
I just made a small modification to his answer, checking the array and the sum value is not null, this is my last 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); };
javascript arrays angularjs prototype-programming
nramirez Apr 23 '14 at 2:47 april 2014-04-23 14:47
source share