Group hashes by keys and sum the values

前端 未结 5 2123
情话喂你
情话喂你 2020-11-27 03:50

I have an array of hashes:

[{\"Vegetable\"=>10}, {\"Vegetable\"=>5}, {\"Dry Goods\"=>3>}, {\"Dry Goods\"=>2}]

I need to use

5条回答
  •  孤街浪徒
    2020-11-27 04:12

    I'm not sure that a hash is what you want here, because I don't multiple entries in each hash. so I'll start by changing your data representation a little.

    ProductCount=Struct.new(:name,:count)
    data = [ProductCount.new("Vegetable",10),
            ProductCount.new("Vegetable",5),
            ProductCount.new("Dry Goods",3),
            ProductCount.new("Dry Goods",2)]
    

    If the hashes can have multiple key-value pairs, then what you probably want to do is

    data = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]
    data = data.map{|h| h.map{|k,v| ProductCount.new(k,v)}}.flatten
    

    Now use the facets gem as follows

    require 'facets'
    data.group_by(&:name).update_values{|x| x.map(&:count).sum}
    

    The result is

    {"Dry Goods"=>5, "Vegetable"=>15}
    

提交回复
热议问题