Pregunta

I managed to reduce and combine my Price Amount Object with this:

stooges = [{Price: 1.2, Amount: 40}, {Price: 1.3, Amount: 50}, {Price: 1.2, Amount: 60}];


inputarray = _.map  _.groupBy(stooges, 'Price'), (v, k) -> 
        {  Price: k
        Amount : _.reduce(v, ((m, i) -> m + i['Amount']), 0)}

console.log(inputarray)

Creates the following

[Object { Price="1.2", Amount=100}, Object { Price="1.3", Amount=50}]

But maybe the grouping is to much. anyhow i try to end up like this

[ { 1.2 : 100 } , { 1.3 : 50 } ]

With the Price as Key and the Amount as Value. Damn i suck at this.

¿Fue útil?

Solución

Try this:

_.map(_.groupBy(stooges, 'Price'), function(v, k){
  var obj = {};
  obj[k] = _.reduce(v, function(m, i){ return m + i['Amount'] }, 0);
  return obj;
})

It returns the following:

[{ "1.2": 100 }, { "1.3": 50 }]

Edit: I'm not sure it's all that helpful to return an array. If you're using Lo-Dash instead of Underscore (which I recommend you do), you can use this instead which will return a single object with all the prices as keys to the total amount:

_(stooges).groupBy('Price').mapValues(function(stooge){
  return _(stooge).pluck('Amount').reduce(function(total, amount){
    return total + amount;
  })
}).value()

It returns the following:

{ "1.2": 100, "1.3": 50 }

Otros consejos

result1 = _.pluck inputarray,'Price'

result2 = _.pluck inputarray,'Amount'

boo = _.object(result1,result2);

Thanks got it now its not that elegant as yours!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top