ruby on rails - Transform hash result of multiple group result set -


this output of product.group([:name, :category]).order([:name, :category]).count:

{   ["product a", "category 2"]=>42,   ["product a", "category 3"]=>83,   ["product a", "category 4"]=>47,   ["product b", "category 2"]=>1,   ["product b", "category 3"]=>4,   ["product b", "category 4"]=>10,   ["product c", "category 3"]=>2,   ["product c", "category 4"]=>4,   ["product d", "category 1"]=>6,   ["product d", "category 2"]=>13,   ["product d", "category 3"]=>57,   ["product d", "category 4"]=>27 } 

each product can of categories 1-4. need have count of 0's final transformation.

desired transformation array columns: product name, count of category 1, count of category 2, count of category 3 , count of category 4:

[   ["product a",  0, 42, 83, 47],   ["product b",  0,  1,  4, 10],   ["product c",  0,  0,  2,  4],   ["product d",  6, 13, 57, 27] ] 

groups.group_by { |(p,_),_| p }.map |product, prod_groups|    [product, *(1..4).map |category|      (prod_groups.find {|(_, c), v| c == "category #{category}" }||[0]).last   end] end # => [["product a", 0, 42, 83, 47], ["product b", 0, 1, 4, 10], ["product c", 0, 0, 2, 4], ["product d", 6, 13, 57, 27]]  

another option arbitrary category names:

category_names = ["category 1", "category 2", "category 3", "category 4"]  groups.group_by { |(p,_),_| p }.map |product, prod_groups|    sub_groups = hash[prod_groups.map { |(p, c), v| [c, v] }]   sub_groups.default = 0   [product, *category_names.map { |c| sub_groups[c] }] end # => [["product a", 0, 42, 83, 47], ["product b", 0, 1, 4, 10], ["product c", 0, 0, 2, 4], ["product d", 6, 13, 57, 27]]  

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -