2014-02-05 56 views
0

似乎_.reduce(或等價的本地函數)的例子非常簡單。有人可以提供一個使用這個函數來求和然後對一系列對象進行排序/排序的例子嗎?例如,如果我的數組包含 -如何使用_.reduce或native 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}] 

什麼是去了解它的最好方法?

回答

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() 
+0

超級騙子的感謝! – oakfish56

相關問題