Pregunta

I managed to do a coffescript map reduce to get out of the database what i need.

    inputarray = _.map  _.groupBy(inputarrayz, 'Price'), (v, k) -> 
        {Price: k, 
        Money_Amount: _.reduce(v, ((m, i) -> m + i['Money_Amount']), 0), 
        Product_Amount: _.reduce(v, ((m, i) -> m + i['Product_Amount']), 0)}
    sorted = _.sortBy inputarray,"Price"
    return sorted

I have a table with the sorted result like this

Price / Money / Product

1 / 2 / 2

2 / 10 / 5

3 / 9 / 3

where product amount is money divided by price. Now i want to have a fourth column to get the combined product count, starting with the first row and counting down. Example:

1 / 2 / 2 / 2 (only 2 products)

2 / 10 / 5 / 7 (5+ the 2 before)

3 / 9 / 3 / 12 (all before + 3)

I tried to do it in jquery cause my head starts to explode when im thinking about map reduce...what resulted in some weird table row before add construct. hope someone could help me out.

Thanks alot.

¿Fue útil?

Solución

A running total is a pretty classic case for reduce. All you need to do is add another reduce after the sorting to compute the running total and stash it in the objects, something like:

running_total = (t, p) -> p.Total = t + p.Product
_(sorted).reduce running_total, 0

That will give you a sorted like this:

sorted = [
    { Price: 1, Money:  2, Product: 2, Total:  2 }
    { Price: 2, Money: 10, Product: 5, Total:  7 }
    { Price: 3, Money:  9, Product: 3, Total: 10 }
]

Demo: http://jsfiddle.net/ambiguous/e5duF/

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