简体   繁体   English

合并具有相同键但值不同的哈希数组并添加值

[英]Merge an array of hashes that have the same key but different value and add the value

Hello i have a hash that loos similar to this 您好,我有一个与此类似的哈希

@receivers
=> [{:amount=>50, :email=>"user_02@example.com"},
 {:amount=>50, :email=>"user_02@example.com"},
 {:amount=>50, :email=>"user_02@example.com"},
 {:amount=>100, :email=>"user_01@example.com"},
 {:amount=>100, :email=>"user_01@example.com"}]

How do i make it look like this?: 我如何使它看起来像这样?:

@receivers
=> [{:amount=>150, :email=>"user_02@example.com"}
 {:amount=>200, :email=>"user_01@example.com"}]

Thank you for your help. 谢谢您的帮助。

You can calculate it like this: 您可以这样计算:

@receivers.group_by { |e| e[:email] }
          .map { |k, v| { amount: v.sum { |e| e[:amount] }, email: k } }



#=> [{:amount=>150, :email=>"user_02@example.com"},
#    {:amount=>200, :email=>"user_01@example.com"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM