EricLarch
EricLarch

Reputation: 5773

How to efficiently merge hashes by key

I have the following array

 [ {"date"=>"July 2013", "view"=>12245}, 
   {"date"=>"July 2013", "click"=>916}, 
   {"date"=>"August 2013", "view"=>34889}, 
   {"date"=>"August 2013", "click"=>2012} ]

And here is the desired output:

 [ {"date"=>"July 2013", "view"=>12245, "click"=>916},
   {"date"=>"August 2013", "view"=>34889, "click"=>2012} ]

What would be the most efficient implementation?

Upvotes: 0

Views: 75

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118289

ar = [ {"date"=>"July 2013", "view"=>12245}, 
   {"date"=>"July 2013", "click"=>916}, 
   {"date"=>"August 2013", "view"=>34889}, 
   {"date"=>"August 2013", "click"=>2012} ]

ar.group_by{|h| h["date"]}.map{|k,v| v.inject(:merge)}
# => [{"date"=>"July 2013", "view"=>12245, "click"=>916},
#     {"date"=>"August 2013", "view"=>34889, "click"=>2012}]

Upvotes: 2

Related Questions