Cacomania: Simple AngularJS sum by key view filter

Cacomania

Simple AngularJS sum by key view filter

Guido Krömer - 2. December 2013 - Tags: ,

This little view filter for AngularJS sums up the values of a spcific field from an array of objects.

This is quite useful if you want to show the total number of something at a table footer, for example.

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;
        };
    });

Here is a small fiddle which shows how the filter works:

Let me know if you liked or disliked my little posting.