i'm having trouble of making second groupby
, doing math: total
, difference
, total
sum() positive number , diffenrence
sum() negative number.
this got:
[ ["category":"beer", "name":"budweiser", "type":null, "price":50.00, "quantity":2], ["category":"soft drink", "name":"pepsi", "type":null, "price":10.00, "quantity":5], ["category":"soft drink", "name":"pepsi", "type":null, "price":10.00, "quantity":-5], ["category":"soft drink", "name":"coke", "type":null, "price":10.00, "quantity":3], ["category":"soft drink", "name":"pepsi", "type":null, "price":10.00, "quantity":7], ["category":"alchool", "name":"smir", "type":18, "price":5.00, "quantity":1], ["category":"alchool", "name":"smir", "type":18, "price":5.00, "quantity":-1], ["category":"alchool", "name":"bala", "type":20, "price":5.00, "quantity":5] ]
and i'm trying get:
[ [beer: [name: budweiser, type: null, price: 50.00, total: 2, difference: 0] ], [softdrink: [name: coke, type: null, price: 10.00, total: 3, difference: 0], [name: pepsi, type: null, price: 10.00, total: 12, difference: 5] ], [achool: [name:smir, type:18, price: 5.00, total: 1, difference: 1], [name:bala, type:20, price: 5.00, total: 5, difference: 0]] ]
my code i'm trying:
products.groupby { it.category }.collectentries { k, v -> [k, v.collect{ c-> [name: c.name, difference: c.quantity, total: v.quantity.sum() + math.abs(c.quantity)] }] }
try :
products.groupby { it.category }.collectentries { category, product -> [(category): product.groupby { it.name }.collect { name, p -> [ name:name, type: p[0].type, price:p[0].price, total:p.quantity.sum { math.max(0, it) }, difference:p.quantity.sum { math.max(0, -it)} ]} ] }
nb: https://groovyconsole.appspot.com/script/5093590829105152
with 'double groupby' (it's not more simple, because want rewrite nested data) :
products.groupby({ it.category }, {it.name}).collectentries { category, names -> [(category): names.collect { name, p -> [ name:name, type: p[0].type, price:p[0].price, total:p.quantity.sum { math.max(0, it) }, difference:p.quantity.sum { math.max(0, -it)} ] } ] }
Comments
Post a Comment