0

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"}]
tardjo
  • 1,594
  • 5
  • 22
  • 38

4 Answers4

1

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}] 
Rafa Paez
  • 4,820
  • 18
  • 35
0
[{"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"}]
sawa
  • 165,429
  • 45
  • 277
  • 381
0

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}]
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
-1

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"}]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317