简体   繁体   English

如何在具有重复红宝石的数组中查找公共元素

[英]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'] city & desired_location给出['london']

but I want ['london', 'london', 'london'] 但是我想要['london', 'london', 'london']

You can use Enumerable#select 您可以使用Enumerable#select

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

If desired_location contains a single element: 如果desired_location包含单个元素:

desired_location = ['london']

I recommend @santosh's solution, but this also works: 我建议使用@santosh的解决方案,但这也可以:

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包含多个元素(我认为这是一种可能,否则就不需要将其作为数组了):

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

@Santosh' method returns: @Santosh'方法返回:

["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} 

Another way: 其他方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM