javascript - Find array fields sum using lodash or underscorejs -
i have requirement find sum of "count" fields each "type". there way same using lodash or underscore js. appreciated. thank you.
input array
array = [ { type: 'weibo', count: 1 }, { type: 'xing', count: 1 }, { type: 'twitter', count: 1 }, { type: 'twitter', count: 1 }, { type: 'facebook', count: 1 }, { type: 'facebook', count: 1 }, { type: 'facebook', count: 1 } ] expected output
output = [ { type: 'weibo', count: 1 }, { type: 'xing', count: 1 }, { type: 'twitter', count: 2 }, { type: 'facebook', count: 3 } ]
you _.countby() , _.map(); note that, due midway conversion object, order of output array may not same.
var array = [ { type: 'weibo', count: 1 }, { type: 'xing', count: 1 }, { type: 'twitter', count: 1 }, { type: 'twitter', count: 1 }, { type: 'facebook', count: 1 }, { type: 'facebook', count: 1 }, { type: 'facebook', count: 1 } ]; console.log(_.map(_.countby(array, 'type'), function(value, key) { return { type: key, count: value }; })); <script src="http://underscorejs.org/underscore.js"></script>
Comments
Post a Comment