Reputation: 153
i know this is a simple question but its so frustating for me, i tried many hours and i didnt make it, so i hope can find the answer,
i have array of hashes like this
array = [{date: 1, branch: 1, value: "100"}, {date: 1, branch: 2, value: "200"}, {date: 2, branch: 1, value: "500"}, {date: 3, branch: 2, value: "500"}, {date: 3, branch: 3, value: "300"}]
and i want to grouping it like this
data = [{date: 1, 1: "100", 2: "200"}, {date: 2, 1: "500"}, {date: 3, 2: "500", 3: "300"}]
in the array = [{date: 1, branch: 1, value: "100"}, i want to take the value of branch and value and combine it like this 1: "100"
anyway i can do that, there is no problem if there is using loop or case when method
Upvotes: 0
Views: 91
Reputation: 386
Another solution
array = [{date: 1, branch: 1, value: "100"}, {date: 1, branch: 2, value: "200"}, {date: 2, branch: 1, value: "500"}, {date: 3, branch: 2, value: "500"}, {date: 3, branch: 3, value: "300"}]
data = array.inject({}) do |res, val|
if res[val[:date]]
res[val[:date]].merge!({val[:branch] => val[:value]})
else
res.merge!(val[:date] => {val[:branch] => val[:value]})
end
res
end
puts data.collect{|key, val| {date: key}.merge!(val)}
Upvotes: 1
Reputation: 12558
Probably could be shortened, but it works:
array.group_by { |h| h[:date] }.map do |k, v|
[:date, k, *v.map { |h| [h[:branch], h[:value]] }]
end.map { |x| Hash[*x.flatten] }
# => [{:date=>1, 1=>"100", 2=>"200"}, {:date=>2, 1=>"500"}, {:date=>3, 2=>"500", 3=>"300"}]
Upvotes: 3