Reputation: 5773
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
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