1

I have an set of Arrays. The number of Arrays is dynamic, it could be one, could be 100. In this example it's 3:

arr = [[1,2,3,4], [2,4], [2,3,4]]

What I need as result is to find same (intersecting) value(s) from all arrays. So result should be:

#=> [2,4]

How it could be done a proper way?

2
  • Have you already looked at the simpler 2 case example? stackoverflow.com/questions/10230227/… Commented Jul 21, 2015 at 13:36
  • Sure. But my arr is dynamic as I mentioned before. It could be [[1] [1,2,3,4]] or like it the example above. Commented Jul 21, 2015 at 13:39

2 Answers 2

6

You can use Array#& to find the (set) intersection of arrays:

arr.inject(:&)
# => [2, 4]
Sign up to request clarification or add additional context in comments.

Comments

5
arr.reduce &:&
#⇒ [
#  [0] 2,
#  [1] 4
# ]

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.