tmartin314 tmartin314 - 1 year ago 65
Ruby Question

Sum of a property inside multiple, similar arrays

We have arrays of hashes, each of which has a

property and a

result1 = [
{"value"=>1, "timeframe"=>{"start"=>"2016-05-27T00:00:00.000Z", "end"=>"2016-05-28T00:00:00.000Z"}},
{"value"=>1, "timeframe"=>{"start"=>"2016-05-28T00:00:00.000Z", "end"=>"2016-05-29T00:00:00.000Z"}},
{"value"=>1, "timeframe"=>{"start"=>"2016-05-29T00:00:00.000Z", "end"=>"2016-05-30T00:00:00.000Z"}}

result2 = [
{"value"=>2, "timeframe"=>{"start"=>"2016-05-27T00:00:00.000Z", "end"=>"2016-05-28T00:00:00.000Z"}},
{"value"=>2, "timeframe"=>{"start"=>"2016-05-28T00:00:00.000Z", "end"=>"2016-05-29T00:00:00.000Z"}},
{"value"=>2, "timeframe"=>{"start"=>"2016-05-29T00:00:00.000Z", "end"=>"2016-05-30T00:00:00.000Z"}}

We need to build an array of hashes that hold each date and the sum of the values for it, something like:

[{total: 3, date: 2016-05-28T00:00:00.000Z}, ...]

with a list of values summed up for each day.

I have been playing with variations of map, but am not sure how to make this easier to read and simple.

Answer Source
[result1, result2].reduce(:+)
                  .map { |e| [e['timeframe']['start'], e['value']] }
                  .each_with_object( { |(d, v), memo| memo[d] += v }  
#⇒ {
#     "2016-05-27T00:00:00.000Z" => 3,
#     "2016-05-28T00:00:00.000Z" => 3,
#     "2016-05-29T00:00:00.000Z" => 3
# }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download