How to combine the value of multiple hashes within an array by the same key

I have an array of hashes like so:

[{"apple"=>5}, {"banana"=>4}, {"orange"=>6}, {"apple"=>4}, {"orange"=>2}]

How I do get to:

[{"apple"=>9}, {"banana"=>4}, {"orange"=>8}]

--------------------------------------------------------------------------------------

There are many ways, as you will soon see. Here's one:

arr = [{"apple"=>5}, {"banana"=>4}, {"orange"=>6}, {"apple"=>4}, {"orange"=>2}]

arr.flat_map(&:to_a)
   .group_by(&:first)
   .map { |k,a| { k=>(a.reduce(0) { |tot,(_,v)| tot+v }) } } 
  #=> [{"apple"=>9}, {"banana"=>4}, {"orange"=>8}]

The steps:

a = arr.flat_map(&:to_a)
  #=> [["apple",5], ["banana",4], ["orange",6], ["apple",4], ["orange",2]] 
b = a.group_by(&:first)
  #=> {"apple"=>[["apple", 5], ["apple", 4]],
  #   "banana"=>[["banana", 4]],
  #   "orange"=>[["orange", 6], ["orange", 2]]} 
b.map { |k,a| { k=>(a.reduce(0) { |tot,(_,v)| tot+v }) } }
  #=> [{"apple"=>9}, {"banana"=>4}, {"orange"=>8}] 
```````````````````````````````````````````````````````````
cache = Hash.new { |h, k| h[k] = { k => 0 } }
aoh.flat_map(&:to_a)
   .each_with_object(cache) { |(k,v),h| h[k][k] += v }
   .values


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章