MANEESHA S
MANEESHA S

Reputation: 19

how to combine 2 arrays in rails such that there are no duplicates

Consider I have 2 arrays,

o = ["16", "16", "119"]
d = ["97", "119", "97"]

Output that is needed is like this:

{16=>[97, 119], 119=>[97]}

I tried using .zip but it didn't work. How do I do it?

Upvotes: 1

Views: 87

Answers (3)

Ray Toal
Ray Toal

Reputation: 88378

First thing that comes to mind is this:

result = Hash.new { |h, k| h[k] = [] }
o.zip(d) { |a, b| result[a] << b }
result #=> {"16"=>["97", "119"], "119"=>["97"]}

There probably is a better way though, but this should get you thinking.

Upvotes: 4

sawa
sawa

Reputation: 168101

o.map(&:to_i).zip(d.map(&:to_i)).group_by(&:first).each_value{|a| a.map!(&:last)}
# => {16=>[97, 119], 119=>[97]}

Upvotes: 3

Stefan
Stefan

Reputation: 114178

You could chain group_by and with_index to group the elements in d by the corresponding element in o:

d.group_by.with_index { |_, i| o[i] }
#=> {"16"=>["97", "119"], "119"=>["97"]}

To get integers, you have to add some to_i calls:

d.map(&:to_i).group_by.with_index { |_, i| o[i].to_i }
#=> {16=>[97, 119], 119=>[97]}

Upvotes: 4

Related Questions