Skip to content

Instantly share code, notes, and snippets.

@Cacodaimon
Created November 4, 2013 21:12
Show Gist options
  • Save Cacodaimon/7309268 to your computer and use it in GitHub Desktop.
Save Cacodaimon/7309268 to your computer and use it in GitHub Desktop.
A simple AngularJS filter for summarizing the values of an array containing objects by a key.
<!-- $scope.myList = [{name: 'Foo', total: 1}, {name: 'Bar', total: 2}, {name: 'Baz', total: 3}] -->
<span class="badge badge-success pull-right">{{myList|sumByKey:'total'}}</span>
angular.module('caco.feed.filter', [])
.filter('sumByKey', function() {
return function(data, key) {
if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
return 0;
}
var sum = 0;
for (var i = data.length - 1; i >= 0; i--) {
sum += parseInt(data[i][key]);
}
return sum;
};
});
@meaq79
Copy link

meaq79 commented Nov 8, 2016

I have a issue when key propierty don't exists and other times yes... so... I just add some like this:

if (data[i][key]) {
sum += parseInt(data[i][key]);
}

@samkadam
Copy link

is there any textbox sum example with angularjs ng-repeat

@tinyCoder32
Copy link

Amazing man! thank you!

@Vampire-V
Copy link

data ?

@sanjeevkse
Copy link

Amazing. Super.

@binujoseph1
Copy link

Great Thank you,I have a problem,I have pagination with table.The sum is showing for each page,How can i get grand total instead of page wise torals

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment