Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and sum array of hashes by date

Tags:

arrays

ruby

hash

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}]
like image 617
Shpigford Avatar asked Jan 12 '23 07:01

Shpigford


1 Answers

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}]
like image 127
Arup Rakshit Avatar answered Jan 17 '23 20:01

Arup Rakshit