Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two array of hashes based on hash's value?

Tags:

arrays

ruby

hash

How do I turn this:

first_array = [
  {:count=>nil, :date=>"Jan 31"},
  {:count=>nil, :date=>"Feb 01"},
  {:count=>nil, :date=>"Feb 02"},
  {:count=>nil, :date=>"Feb 03"},
  {:count=>nil, :date=>"Feb 04"},
  {:count=>nil, :date=>"Feb 05"}
]

second_array = [
  {:count=>12, :date=>"Feb 01"},
  {:count=>2, :date=>"Feb 02"},
  {:count=>2, :date=>"Feb 05"}
]

Into this:

result = [
  {:count=>nil, :date=>"Jan 31"},
  {:count=>12, :date=>"Feb 01"},
  {:count=>2, :date=>"Feb 02"},
  {:count=>nil, :date=>"Feb 03"},
  {:count=>nil, :date=>"Feb 04"},
  {:count=>2, :date=>"Feb 05"}
]

I have found similar questions on SO, but none were as simple as this one. There's probably a method/block-combination I should use I don't know of.

like image 720
Marc Avatar asked Jan 20 '23 07:01

Marc


1 Answers

result_array = first_array.map do |first_hash| 
  second_array.each do |second_hash|
    if first_hash[:date] == second_hash[:date]
      first_hash[:count] = second_hash[:count]
      break
    end
  end
  first_hash
end
like image 177
rubyprince Avatar answered Jan 29 '23 08:01

rubyprince