Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lodash to sum values by key

How can I sum the values in objects which share a common key? I need to use Lodash for this because I need good performance if these arrays get huge.

var prjMgrValues = [    {"proj_mgr":"Jack ProjManager","submitted_dollars":12000},    {"proj_mgr":"Jack ProjManager","submitted_dollars":750000},    {"proj_mgr":"Joe ProjManager","submitted_dollars":45000} ] 

I'm looking for an output of

[   {"proj_mgr":"Jack ProjManager","submitted_dollars":762000},   {"proj_mgr":"Joe ProjManager","submitted_dollars":45000} ] 
like image 621
S. Hussey Avatar asked Aug 04 '16 18:08

S. Hussey


People also ask

How do you use sumBy in Lodash?

sumBy() method is used to compute the sum from the original array by iterating over each element in the array by using the Iteratee function. It is almost the same as _. sum() method.


1 Answers

This is a case of reduction for each unique element.

I always use _.groupBy and then _.map the result to an array after applying the reduction. In this case the reduction operation is _.sumBy.

var prjMgrValues = [     {"proj_mgr":"Jack ProjManager","submitted_dollars":12000},     {"proj_mgr":"Jack ProjManager","submitted_dollars":750000},     {"proj_mgr":"Joe ProjManager","submitted_dollars":45000}  ];    var output =    _(prjMgrValues)      .groupBy('proj_mgr')      .map((objs, key) => ({          'proj_mgr': key,          'submitted_dollars': _.sumBy(objs, 'submitted_dollars') }))      .value();    console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"></script>
like image 146
4castle Avatar answered Oct 01 '22 18:10

4castle