Merge values with the same key
ruby, ruby-on-rails, ruby-on-rails-3
Solution
Simple as that:
a.inject({}) { |h,(date, count)| h[date] ||= 0; h[date] += count; h }.to_a
Problem
I need to values for a graph, and I want all values with the same date to merge. This is the array I have now: ``` [ ['2012-10-09', 1], ['2012-10-09', 2], ['2012-10-10', 1], ['2012-10-10', 4], ['2012-10-10', 1], ['2012-10-11', 3] ] ``` And the result I want: ``` [ ['2012-10-09', 3], ['2012-10-10', 6], ['2012-10-11', 3] ] ``` Is there a simple way to do this?