Skip to content

Instantly share code, notes, and snippets.

@WindSaber
Forked from Cacodaimon/SumByKey.js
Last active May 30, 2016 16:13
Show Gist options
  • Save WindSaber/ae4c5d7ea689b36990b5545d1e4a91ac to your computer and use it in GitHub Desktop.
Save WindSaber/ae4c5d7ea689b36990b5545d1e4a91ac to your computer and use it in GitHub Desktop.
Fork of the original gist https://gist.github.com/Cacodaimon/7309268 with improvements (support fot objects Not ony arrays and floats instead of just int values)
<!-- $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;
angular.forEach(data, function(obj, objKey){
sum+= parseFloat(obj[key]);
});
return sum;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment