Ruby on Rails - Hash of Arrays, group by and sum by column name

后端 未结 1 668
粉色の甜心
粉色の甜心 2021-01-16 20:28

I have the following array of hashes:

[{\"idx\"=>\"1234\", \"account\"=>\"abde\", \"money\"=>\"4.00\", \"order\"=>\"00001\"}, {\"idx\"=>\"1235\", \"

相关标签:
1条回答
  • 2021-01-16 20:48

    you can make your own method for that, something like:

    def group_hashes arr, group_field, sum_field
      arr.inject({}) do |res, h|
        (res[h[group_field]] ||= {}).merge!(h) do |key, oldval, newval|
          key.eql?(sum_field) ? (oldval.to_f + newval.to_f).to_s : oldval
        end
        res
      end.values
    end
    

    a call group_hashes arr, "order", "money" on you array of hashes example returns:

    [{"idx"=>"1234", "account"=>"abde", "money"=>"6.0", "order"=>"00001"}, {"idx"=>"1235", "account"=>"abde", "money"=>"3.00", "order"=>"00002"}]
    
    0 讨论(0)
提交回复
热议问题