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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值