i want to sum values inside array hash with same key in ruby, example :
a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
how to make the array of hash to like this :
a = [{"nationalvoice"=>"6"}]
My functional solution
array = [{"foo" => "1"}, {"bar" => "2"}, {"foo" => "4"}]
array.group_by { |h| h.keys.first }.map do |k, v|
Hash[k, v.reduce(0) { |acc, n| acc + n.values.first.to_i }]
end
# => [{"foo"=>5}, {"bar"=>2}]
[{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
.group_by{|h| h.keys.first}.values
.map{|a| {
a.first.keys.first =>
a.inject(0){|sum, h| sum + h.values.first.to_i}.to_s
}}
# => [{"nationalvoice"=>"6"}]
Simple way:
[{ "nationalvoice" => [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}].reduce(0) {|s, v| s + v.values.first.to_i } }]
# => [{"nationalvoice"=>6}]
with #replace
:
a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
a.replace( [{ a.first.keys.first => a.reduce(0) {|s, v| s + v.values.first.to_i } }] )
# => [{"nationalvoice"=>6}]
I'd do as below :
a = [{"nationalvoice"=>"1"}, {"foo" => "1"}, {"bar" => "2"}, {"nationalvoice"=>"5"}]
new = a.group_by { | h | h.keys.first }.map do |k,v|
v.each_with_object({}) do | h1,h2|
h2.merge!(h1) { |key,old,new| (old.to_i + new.to_i).to_s }
end
end
new # => [{"nationalvoice"=>"6"}, {"foo"=>"1"}, {"bar"=>"2"}]