Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge same hashes in array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading