2

I've got an Array of arrays. There can be two or more subarrays:

array = [
  ["66892885", "66891801", "66924833", "66892255"],
  ["65167829", "65167828", "66924833"],
  ["66924833", "66891801"]
]

I need only the values found across each subarray. So in this case "66924833" would be the only match. For a value to show up in the result, each subarray has to contain it.

How can I do this?

5
  • what would the return be if there are more than 2 sub arrays? Commented Oct 14, 2019 at 22:19
  • @lusketeer even if there are 10 sub arrays, I still need the shared values across all 10 Commented Oct 14, 2019 at 22:21
  • so for [[a, b], [b, c], [a, c]] would return []? Commented Oct 14, 2019 at 22:22
  • @lusketeer yes...but the way my data is configured, there will ALWAYS be a match Commented Oct 14, 2019 at 22:23
  • 1
    okay, someone already posted what I wanted to post, should work for your case Commented Oct 14, 2019 at 22:24

1 Answer 1

3

You can combine inject with Array's Set Intersection (#&) method like this

array.inject(:&)

to get the desired result:

array=[["66892885", "66891801", "66924833", "66892255", "1", "33"],
       ["65167829", "65167828", "66924833", "1", "33", "44"], 
       ["2344", "66924833", "1", "33"]]

array.inject(:&)
#=>["66924833", "1", "33"]
Sign up to request clarification or add additional context in comments.

1 Comment

Since & has special meaning in Ruby's syntax, it might be worth noting that here :& is merely a symbol referring to the operator method Array#&. So [a, b, c].inject(:&) translates to a & b & c

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.