Skip to content

Instantly share code, notes, and snippets.

@voznik
Forked from Cacodaimon/SumByKey.js
Last active September 10, 2015 14:18
Show Gist options
  • Save voznik/45d2ad832251fbeecd95 to your computer and use it in GitHub Desktop.
Save voznik/45d2ad832251fbeecd95 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;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment