似乎_.reduce(或等效的本机函数)的示例非常简单。有人可以提供一个使用此函数求和然后对对象数组进行排序/排序的示例吗?例如,如果我的数组包含 -
[{ name: 'John', store: 23, revenue: 300.00 },
{ name: 'John', store: 23, revenue: 600.00 },
{ name: 'Kerry', store: 23, revenue: 100.00 },
{ name: 'Kerry', store: 23, revenue: 200.00 },
{ name: 'Lars', store: 24, revenue: 600.00 },
{ name: 'Lars', store: 24, revenue: 800.00 },
{ name: 'Lars', store: 24, revenue: 1000.00 },
{ name: 'Indira', store: 24, revenue: 1800.00 },
{ name: 'Indira', store: 24, revenue: 2800.00 },
{ name: 'Indira', store: 24, revenue: 3800.00 },
{ name: 'Jacinta', store: 24, revenue: 300.00 }]
我希望输出如下:
[{store: 23, rank: 1, name: 'John', revenue: 900.00},
{store: 23, rank: 2, name: 'Kerry', revenue: 300.00},
{store: 24, rank: 1, name: 'Indira', revenue: 8400.00},
{store: 24, rank: 2, name: 'Lars', revenue: 2400.00},
{store: 24, rank: 3, name: 'Jacinta', revenue: 300.00}]
最好的方法是什么?
答案 0 :(得分:2)
这个小怪物似乎在做这个工作:
result = _(data).chain().groupBy('name').map(function(g) {
return {
name:g[0].name,
store:g[0].store,
revenue: _.reduce(g, function(a, b) { return a + b.revenue}, 0)
}
}).sortBy('revenue').reverse().groupBy('store').map(function(g) {
return _(g).chain().map(function(x, n) {
return x.rank = n + 1, x;
}).value()
}).values().flatten().value()