S. Hussey S. Hussey - 4 months ago 35
Javascript Question

Using Lodash to sum values by key

I've been circling the drain on this one through so many different solutions but each one didn't quite do what I wanted.

I need to use lodash for this - (a performance thing in my opinion as these arrays could 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}
]


Go.. should be simple for someone who knows lodash.

Answer

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((v, k) => ({ 
      proj_mgr: k,
      submitted_dollars: _.sumBy(v, 'submitted_dollars')
  })).value();

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"></script>

Comments