Hari Krishnan
Hari Krishnan

Reputation: 1166

how to find common element in array with duplicates ruby

Lets say array look like below

city = ['london', 'new york', 'london', 'london', 'washington']

desired_location = ['london']

city & desired_location gives ['london']

but I want ['london', 'london', 'london']

Upvotes: 0

Views: 808

Answers (3)

Santhosh
Santhosh

Reputation: 29124

You can use Enumerable#select

city.select {|c| desired_location.include?(c)}
# => ["london", "london", "london"]

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

cities = ['london', 'new york', 'london', 'london', 'washington']

If desired_location contains a single element:

desired_location = ['london']

I recommend @santosh's solution, but this also works:

desired_location.flat_map { |c| [c]*cities.count(c) }
  #=> ["london", "london", "london"]

Suppose desired_location contains multiple elements (which I assume is a possibility, for otherwise there would be no need for it to be an array):

desired_location = ['london', 'new york']

@Santosh' method returns:

["london", "new York", "london", "london"]

which is quite possibly what you want. If you'd prefer that they be grouped:

desired_location.flat_map { |c| [c]*cities.count(c) }
  #=> ["london", "london", "london", "new york"]

or:

desired_location.map { |c| [c]*cities.count(c) }
  #=> [["london", "london", "london"], ["new york"]]

Depending on your requirements, you might find it more useful to produce a hash:

Hash[desired_location.map { |c| [c, cities.count(c)] }]
  #=> {"london"=>3, "new york"=>1} 

Upvotes: 1

jeton
jeton

Reputation: 921

Another way:

cities = ['london', 'new york', 'london', 'london', 'washington']
puts cities.select{|city| cities.count(city) > 1}

Upvotes: 0

Related Questions