如何执行 groupBy 并添加 underscore.js 中分组的值的总和

How to do groupBy and add the sum of the values grouped in underscore.js

来自这里:

var x = [ 
    {category: 'Title', price: 100 }, 
    {category: 'Title', price: 200 },
    {category: 'Title3', price: 300 },
    {category: 'Title3', price: 400 },
    {category: 'Title5', price: 500 },
];

为此:

var x = [
    {category: 'Title', price: 300},
    {category: 'Title3', price: 700},
    {category: 'Title5', price: 500},
];            

逻辑同SQL查询:

SELECT category, sum (price) FROM x GROUP BY category;

更新:

  1. groupBy 将按 "category".
  2. 对初始数组进行分组
  3. map 然后将通过传入两个参数来迭代分组数组中的每个对象:keyvalue。第一个 key 将是 "Title",它的 value[{category: 'Title', price: 100 }, {category: 'Title', price: 200 }].
  4. 的数组
  5. 在return更新map中的数组之前,reduce用于总结"price"。基本上,它遍历数组(第一个参数)和 return 函数的总和(第二个参数)。请注意,在第一次迭代中,total 将是 0reduce 中的最后一个参数)。因此,第一个 return 将是 0 + 100,然后在第二次迭代中作为 'new' total 传入,依此类推。

详情请参考documentation

试试这个:

var groups = _.groupBy(x, 'category');
var result = _.map(groups, function(value, key) {
  return { 
    category: key, 
    price: _.reduce(value, function(total, o) { 
        return total + o.price;
    }, 0) 
  };
});