Question

It seems as though the examples for _.reduce (or the equivalent native function) are very simplistic. Could someone provide an example of using this function to sum and then rank/sort an array of objects? For example, if my array contains --

[{ 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 }]

And I want the output to be as follows:

[{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}]

What's the best way to go about this?

Was it helpful?

Solution

This little monster seems to do the job:

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top