简体   繁体   中英

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"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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