Home > Enterprise >  How to merge same hashes in array?
How to merge same hashes in array?

Time:11-09

If I have

array = [{:external_product_id=>"A", :quantity=>1}, {:external_product_id=>"A", :quantity=>2}, {:external_product_id=>"B", :quantity=>1}]

and want to transform into

array = [{:external_product_id=>"A", :quantity=>3}, {:external_product_id=>"B", :quantity=>1}] 

like, merging products with the same id ("A") together. Is there any easier way without using map, select, etc?

I am trying it now with using map and seems a bit harder than I expected.

CodePudding user response:

anything like this?

array.group_by { |item| item[:external_product_id] }
     .map do |external_product_id, items| 
       { 
         external_product_id: external_product_id, 
         quantity: items.sum { |item| item[:quantity] }
       } 
     end

=> [{:external_product_id=>"A", :quantity=>3}, {:external_product_id=>"B", :quantity=>1}]
  • Related