Means
Means

Reputation: 432

Ruby Extract array from multi-dimensional array

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?

Upvotes: 1

Views: 491

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52357

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? }

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

arr1.select { |(_, d)| arr2.include? d }

Upvotes: 1

Ursus
Ursus

Reputation: 30056

Try this one

arr1.select { |a| a.any? { |item| arr2.include? item } }
 => [["text2", 2], ["&nbsp;&nbsp;&nbsp;&nbsp;text3", 3], ["text6", 6]] 

Upvotes: 3

Related Questions