user3291025
user3291025

Reputation: 1117

Ruby: 2 arrays merge to keep duplicates

I have searched the array methods and enumerable methods and not found any way to do this. How do merge two arrays into one array, discarding the unique values and keeping only the duplicates?

Array1 = [1, 2, 3, 4, 5, 6] Array2 = [3, 4, 5, 6, 7, 8]

. . .

Array_Result = [3, 4, 5, 6 ]

Upvotes: 1

Views: 1532

Answers (3)

jorgenj
jorgenj

Reputation: 31

It sounds to me like the OP wants to merge two arrays, then discard anything that is NOT duplicated in the resulting array. If that's the case, I think the following will do the trick:

a3 = (array1 + array2)

# narrow it down to an array only the values which were duplicated
a3.inject(Hash.new(0)) { |hash,val| 
  hash[val] += 1
  hash 
}.each_pair.select { |(val,count)| 
  count > 1 
}.map { |(val,count)| 
  val 
}

This removes duplicates, but the OP's example seems to indicate that as a goal.

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

I prefer Uri's answer, but this also works:

array1.uniq - (array1-array2)
  #=> [3, 4, 5, 6]

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37409

If what you want is only the items that appear in both arrays (this is called intersection) - use the & operator:

[1, 2, 3, 4, 5, 6] & [3, 4, 5, 6, 7, 8]
# =>  [3, 4, 5, 6 ]

Upvotes: 9

Related Questions