MBJH
MBJH

Reputation: 1639

How to sort an array of hashes into hashes with multiple values for a key?

I am working on Ruby on Rails project using rails4.

Scenario:

I have an array of hashes. An array contains hashes where keys are the same.

 a = [{132=>[1000.0]}, {132=>[4000.0]}, {175=>[1000.0]}, {175=>[1000.0]}, {133=>[1200.0]}]
 h = a.each {|key,value| key.each {|k| value}}
#{132=>[1000.0]}
#{132=>[4000.0]}
#{175=>[1000.0]}
#{175=>[1000.0]}
#{133=>[1200.0]}

Problem:

How to get rid off duplicate keys but with values added to unique keys like this:

 {132=>[1000,4000]}
 {175=>[1000,1000]}
 {133=>[1200]}

Thank you.

Upvotes: 2

Views: 228

Answers (3)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

This works for me:

p a.each_with_object(Hash.new([])) { |e, h| e.each { |k, v| h[k] += v } }

# => {132=>[1000.0, 4000.0], 175=>[1000.0, 1000.0], 133=>[1200.0]}

Upvotes: 6

Cary Swoveland
Cary Swoveland

Reputation: 110685

Another way:

a.each_with_object({}) do |g,h|
  k, v = g.to_a.flatten
  (h[k] ||= []) << v
end
  #=> {132=>[1000.0, 4000.0], 175=>[1000.0, 1000.0], 133=>[1200.0]}

or

a.each_with_object(Hash.new { |h,k| h[k]=[] }) do |g,h|
  k, v = g.to_a.flatten
  h[k] << v
end
  #=> {132=>[1000.0, 4000.0], 175=>[1000.0, 1000.0], 133=>[1200.0]}

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44685

That would do it:

a.inject({}) {|sum, hash| sum.merge(hash) {|_, old, new| old + new }}

Upvotes: 7

Related Questions