像这样的数组
[{ dep: 'A', qt: 10, price: 5},
{ dep: 'A', qt: 5, price: 2.30 },
{ dep: 'B', qt: 3, price: 2.20 },
{ dep: 'C', qt: 1, price: 4 },
{ dep: 'C', qt: 4, price: 10 }
...etc..
]
分组和求和值的优雅方式是什么,结果如下:
[{ dep: 'A', qt: 15, price: 61.5 },
{ dep: 'B', qt: 3, price: 2.20 },
{ dep: 'C', qt: 5: price: 44 }
]
解决方法:
你可以这样做:
function sumInvoices(p, c) {
return _.extend(p, {qt:p.qt + c.qt, price:p.price + c.qt*c.price});
};
var b = _(a)
.groupBy('dep')
.map(function(b) {return b.reduce(sumInvoices, {dep:b[0].dep, qt:0, price:0})})
.valueOf();