Merge two arrays in Ruby by unique key

  • A+
Category:Languages

How can I merge two arrays with the unique key:

keyList = ["a", "b", "c", "d"]  keyValueList = [   ["a", [1, 2, 3]],   ["a", [4, 5, 6]],   ["b", [5, "a", 3]],   ["b", ["test", 4, 3]],   ["c", [1, "number", 110]] ] 

to get the following?

[   ["a", [[1, 2, 3], [4, 5, 6]]],   ["b", [[5, "a", 3], ["test", 4, 3]]],   ["c", [[1, "number", 110]]] ] 

 


Use Enumerable#group_by:

keyValueList.   map(&:flatten).   group_by(&:shift).   select { |k, _| keyList.include?(k) }.   to_a #⇒ [["a", [[1, 2, 3], [4, 5, 6]]], #   ["b", [[5, "a", 3], ["test", 4, 3]]], #   ["c", [[1, "number", 110]]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: