1

I have a multidimensional array like:

arr1 = [["text1", 1], ["text2", 2], ["    text3", 3], ["    text4", 4], ["text5", 5], ["text6", 6], ["text7", 7]]

and another

arr2 = [2,3,6]

I want to extract entire array if it contains elements of arr2. So, result should be:

arr = [["text2", 2], ["    text3", 3], ["text6", 6]].

I've tried many ways but unable to get the result. Attempts such as:

arr1.each { |elem| arr2.each { |x| elem.delete_if{ |u| elem.include?(x) } } }

and

arr2.map { |x| arr1.map{|key, val| val.include?(x) }}

Can anyone please help?

0

3 Answers 3

3

Try this one

arr1.select { |a| a.any? { |item| arr2.include? item } }
 => [["text2", 2], ["    text3", 3], ["text6", 6]] 
Sign up to request clarification or add additional context in comments.

1 Comment

I prefer this or the first comment of the accepted answer as it is more clearly related to what the code is trying to do, i.e. finding something.
1
arr1.select { |(_, d)| arr2.include? d }

3 Comments

Not very generic solution - having the position of integer in an array changed it will fail, as well as having the arr2 changed will make this solution invalid :) P.S. I know you know
@AndreyDeineko I am not sure I follow. I believe those are dumped elements with ids in arr1 and ids themselves in arr2. It will also fail on non-unique multiple values in arr2 etc, but for the stated question this solution is robust enough.
Whatever those are, the question/request is I want to extract entire array if it contains elements of arr2, which your solution does not satisfy given the input data slightly changed. Even though with the provided examplary input it does solve it. arr1 = [[1, "text1"], [2, 'text'], [5, "text5"], [6, "text6"], [7, "text7"]], which with your solution will result in [], while it should result in [[2, "text"], [6, "text6"]]
0
arr1.inject([]) { |result, array| (array & arr2).any? ? result << array : result }
#=> [["text2", 2], ["&nbsp;&nbsp;&nbsp;&nbsp;text3", 3], ["text6", 6]]

Slightly shorter and more correct from the goal perspective:

arr1.select { |array| (array & arr2).any? }

2 Comments

Why not arr1.select { |a| (a & arr2).any? } or arr1.find_all { |a| (a & arr2).any? } since you are selecting/finding things rather than a more general injection/reduction?
@muistooshort selecting is definitely better than building a new array (which I did), I'll edit the answer (i did not do that before because solutions with select were already given)..

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.