Reputation: 183
I have the following array: items = [[573, 574], [573, 574], [573], [573, 574]]
How to find element which is occurring on each array ? From this array i want to get only "573" Anyone could help me ?
Upvotes: 0
Views: 57
Reputation: 110755
def appears_in_all(arr)
arr.reduce(:&)
end
appears_in_all [[573, 574], [573, 574], [573], [573, 574]] #=> [573]
appears_in_all [[573, 574], [573, 574], [573, 574, 578], [573, 574]] #=> [573, 574]
appears_in_all [[573, 574], [573, 574], [573], [573, 574], [2, 4]] #=> []
Upvotes: 3
Reputation: 11090
You can find the smallest sub array in items
(to limit the search set) and then select all the elements from that array that appear in all the other arrays in items
:
items.min_by(&:length).select do |element|
items.all? { |sub_array| sub_array.include?(element) }
end
# => [573]
if it's guaranteed only a single element is in all of them, you can use detect
instead of select
Upvotes: 3