Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

javascript - 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}
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...