0

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 ?

3 Answers 3

3
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]]   #=> []
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I must use the comments to say is a very clean solution.
1
items.flatten.uniq.select{|x| items.map{|y| y.include? x}.all?}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.