Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 61392  / 8 Years ago, thu, august 4, 2016, 12:00:00

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}
]

More From » lodash

 Answers
3

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>




[#61142] Tuesday, August 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbyw

Total Points: 456
Total Questions: 102
Total Answers: 113

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;