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

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -