Underscore.js:集合中的项目总和 [英] Underscore.js: Sum of items in a collection
本文介绍了Underscore.js:集合中的项目总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里制作了一个小plnkr来展示我想要实现的目标。我有一个很大的数据集,我喜欢总结各个类型以获得总数。
I made a small plnkr here to show what I am trying to achieve. I have a big dataset, where I like to sum the individual type to get a total.
我可以想到迭代并将结果添加到对象哈希,但是奇迹更优雅的方式用下划线解决它。我使用的是underscore.js,但从未尝试过map reduce或其他功能范例。请更新plnkr以了解如何执行此操作。
I could think of iterating and adding the results to an object hash, but wonder more elegant way to solve it with underscore. I am using underscore.js, but never tried map reduce or other functional paradigm. Please update the plnkr to learn how to do this.
http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview
var data = [ {'type': "A", 'val':2},
{'type': "B", 'val':3},
{'type': "A", 'val':1},
{'type': "C", 'val':5} ];
_.each(data, function (elm, index) {
console.log(elm);
});
/*
Desired output
out = [ {'type': "A", 'total':3},
{'type': "B", 'total':3},
{'type': "C", 'total':5} ];
*/
推荐答案
var data = [ { type: "A", val: 2 },
{ type: "B", val: 3 },
{ type: "A", val: 1 },
{ type: "C", val: 5 } ];
var groups = _(data).groupBy('type');
var out = _(groups).map(function(g, key) {
return { type: key,
val: _(g).reduce(function(m,x) { return m + x.val; }, 0) };
});
这篇关于Underscore.js:集合中的项目总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文