Javascript Underscore.js:集合中项目的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14430321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:43:27  来源:igfitidea点击:

Underscore.js: Sum of items in a collection

javascriptunderscore.js

提问by bsr

I made a small plnkr hereto show what I am trying to achieve. I have a big dataset, where I like to sum the individual type to get a total.

我在这里做了一个小的 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.

我可以考虑迭代并将结果添加到对象哈希中,但想知道用下划线解决它的更优雅的方法。我正在使用 underscore.js,但从未尝试过 map reduce 或其他功能范式。请更新 plnkr 以了解如何执行此操作。

http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview

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

 */

回答by Sergey Berezovskiy

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) };
});

DEMO

演示

回答by Nevir

Pretty much the same answer as @GregL, just with a bit more underscore:

与@GregL 的答案几乎相同,只是多了一点下划线:

summed_by_type = _(data).reduce(function(mem, d) {
  mem[d.type] = (mem[d.type] || 0) + d.val
  return mem
}, {})

pairs = _(summed_by_type).map(function(v,k) { return {type: k, total: v} })

回答by GregL

The following will work, but I assume it is similar to what you had in mind. The advantage is that by using an object hash to store the totals, you are indexing on the type which means you don't have to iterate through the hash each time trying to find the object with the right type. Then you iterate through it once at the end to build up the final output array.

以下将起作用,但我认为它与您的想法相似。优点是通过使用对象散列来存储总数,您正在索引类型,这意味着您不必每次尝试查找具有正确类型的对象时都遍历散列。然后在最后迭代它一次以构建最终的输出数组。

Plunkr is here.

Plunkr 在这里

Code is as follows:

代码如下:

var data = [ {'type': "A", 'val':2},
  {'type': "B", 'val':3},
  {'type': "A", 'val':1},
  {'type': "C", 'val':5} ];

var totalPerType = {};
for (var i = 0, len = data.length; i < len; ++i) {
  totalPerType[data[i].type] = totalPerType[data[i].type] || 0;
  totalPerType[data[i].type] += data[i].val;
}
var out = _.map(totalPerType, function(sum, type) {
  return { 'type': type, 'total': sum };
});

 console.log('out = ', out);

EDIT:I have created a new plunkr that generates how fast this is even for a 1 million item array (with 6 possible types) here. As you can see from the console output, at least in Chrome Canary, it runs in about 1/3 second.

编辑:我已经创建了产生这是多么快甚至100万项数组(含6种可能的)的新plunkr这里。从控制台输出中可以看出,至少在 Chrome Canary 中,它的运行时间约为 1/3 秒。

I have also done a jsPerf testfor how much faster it is to use the intermediate hash, and it works out about 50% faster.

我还做了一个jsPerf 测试测试使用中间散列的速度有多快,结果大约快了 50%。