Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Cacodaimon
Created November 4, 2013 21:12
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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;
};
});
@Sampath-Lokuge
Copy link

Really nice one.Thanks for sharing. :)

@bernardolm
Copy link

Good!

@eduardoreche
Copy link

really good stuff. thanks for sharing!

@hidha
Copy link

hidha commented Aug 18, 2015

Thanks for sharing. Was very useful.

@ncarreiro
Copy link

Thank you SO much! You solved a sum problem with a statistics data table I had. Great!

@shadywattay
Copy link

hello, thanks for this helpful filter.
But it seems like, it doesn't sum decimals for a floating value.
35.46 + 20.35 brings 55 instead of 55.81

@WindSaber
Copy link

I've improved it with support for objects instead of just arrays, and support for float values

https://gist.github.com/WindSaber/ae4c5d7ea689b36990b5545d1e4a91ac

Thanks!

@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