I have an array of hashes like this:
[{:created=>Fri, 22 Jan 2014 13:02:13 UTC +00:00, :amount=>20},
{:created=>Fri, 27 Jan 2014 13:14:57 UTC +00:00, :amount=>15},
{:created=>Fri, 27 Jan 2014 14:42:40 UTC +00:00, :amount=>10},
{:created=>Fri, 28 Jan 2014 15:26:58 UTC +00:00, :amount=>10},
{:created=>Fri, 28 Jan 2014 15:30:18 UTC +00:00, :amount=>20},
{:created=>Fri, 31 Jan 2014 15:32:46 UTC +00:00, :amount=>50},
{:created=>Fri, 31 Jan 2014 15:33:29 UTC +00:00, :amount=>40}]
I'd like to group those hashes by date and sum the amounts. So, in my example, the output would be:
[{:created=>"2014-01-22", :amount=>20},
{:created=>"2014-01-27", :amount=>25},
{:created=>"2014-01-28", :amount=>30},
{:created=>"2014-01-31", :amount=>90}]
I'd do as below :
require 'date'
a = [{:created=> 'Fri, 22 Jan 2014 13:02:13 UTC +00:00', :amount=>20},
{:created=>'Fri, 27 Jan 2014 13:14:57 UTC +00:00', :amount=>15},
{:created=>'Fri, 27 Jan 2014 14:42:40 UTC +00:00', :amount=>10},
{:created=>'Fri, 28 Jan 2014 15:26:58 UTC +00:00', :amount=>10},
{:created=>'Fri, 28 Jan 2014 15:30:18 UTC +00:00', :amount=>20},
{:created=>'Fri, 31 Jan 2014 15:32:46 UTC +00:00', :amount=>50},
{:created=>'Fri, 31 Jan 2014 15:33:29 UTC +00:00', :amount=>40}]
hsh = a.group_by { |h| Date.parse h[:created] }.map do |k,v|
{:created => k.to_s,:amount => v.map {|h1| h1[:amount]}.inject(:+)}
end
hsh
# => [{:created=>"2014-01-22", :amount=>20},
# {:created=>"2014-01-27", :amount=>25},
# {:created=>"2014-01-28", :amount=>30},
# {:created=>"2014-01-31", :amount=>90}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With