3

I have a nested "main" array and I am looking to return the results (the entire nested array) for elements matched in a second "match" array. I have been able to return the first value of the arrays desired output using (main && match) but I can find a way into the nested array.

Main:

[[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]

Match:

[222,555,666]

Desired Results:

[[222, [200,201,202]], [555, [500,501,502]], [666, [600,601,602]]]

2 Answers 2

4

This is a perfect place to use Array#assoc:

data = [[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]
match = [222,555,666]

p match.map{|i| data.assoc(i)}

#=> [[222, [200, 201, 202]], [555, [500, 501, 502]], [666, [600, 601, 602]]]

From the docs, Array#assoc

Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==.

Returns the first contained array that matches (that is, the first associated array), or nil if no match is found.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a select to match on the first element in each of the sub-arrays:

data = [[111, [100,101,102]], [222, [200,201,202]], [333, [300,301,302]], [444, [400,401,402]], [555, [500,501,502]], [666, [600,601,602]], [777, [700,701,702]]]

match = [222, 555, 666]

results = data.select{|x| match.include?(x[0])}

p results

#=> [[222, [200, 201, 202]], [555, [500, 501, 502]], [666, [600, 601, 602]]]

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.