Reputation: 27
Having array:
[ { 'a' => 1, 'b' => 1, 'c' => 1, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 1, 'c' => 2, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 1, 'c' => 3, 'd' => 1, 'e' => 2},
{ 'a' => 1, 'b' => 2, 'c' => 4, 'd' => 2, 'e' => 2 },
{ 'a' => 1, 'b' => 2, 'c' => 5, 'd' => 2, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 6, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 7, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 1, 'c' => 8, 'd' => 3, 'e' => 2 },
{ 'a' => 2, 'b' => 2, 'c' => 9, 'd' => 4, 'e' => 2 },
{ 'a' => 2, 'b' => 2, 'c' => 10, 'd' => 4, 'e' => 2 } ]
I want to get max of 'c', sum 'd', sum 'e' grouped by 'a' and 'b'.
So, the result should be:
[ { 'a' => 1, 'b' => 1, 'c' => 3, 'd' => 3, 'e' => 6},
{ 'a' => 1, 'b' => 2, 'c' => 5, 'd' => 4, 'e' => 4},
{ 'a' => 2, 'b' => 1, 'c' => 8, 'd' => 9, 'e' => 6},
{ 'a' => 2, 'b' => 2, 'c' => 10, 'd' => 8, 'e' => 4} ]
So far, I follow How to find max value grouped by multiple keys in array of hashes?, using this code to get max of each group
a.group_by { |h| h.values_at("a", "b") }.map { |_, v| v.max_by { |h| h["c"] } }
Please guide me, get sum too. Thanks a lot.
P/s: using Ruby 1.8.7 and Rails 2.3.5
Upvotes: 0
Views: 564
Reputation: 345
This works:
a.group_by { |h| h.values_at("a", "b") }.map do |_, v|
v.inject { |c, h| c.merge({ "c" => [c["c"], h["c"]].max,
"d" => c["d"] + h["d"],
"e" => c["e"] + h["e"] }) }
end
Upvotes: 1
Reputation: 6537
As you requested in the comments, here's my comment extended into an easier format. My edit to Max's post was rejected.
a.group_by { |h| h.values_at("a", "b") }.
map { |_, v| v.max_by { |h| h["c"] }.
tap { |h| h["d"] = v.inject(0) { |sum, h| sum + h["d"] } }.
tap { |h| h["e"] = v.inject(0) { |sum, h| sum + h["e"] } } }
Upvotes: 1