jay
jay

Reputation: 12495

How to find intersection between an array, and an array of arrays

I have two arrays:

 array1 = [:key1, :key2]
 array2 = [[:key1,2],[:key2,8],[:key3,1]]

I would like to have an array of arrays in array2 whose :key... exists in array1. For example, for the above:

 result = [[:key1,2],[:key2,8]]

Upvotes: 0

Views: 79

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

This works using a quick hash slice:

array1.zip(Hash[array2].values_at(*array1))
=> [[:key1, 2], [:key2, 8]]

It won't work if the key values in array2 ever repeat, because they'll stomp on the previous instances. Otherwise, if they don't repeat, this will be extremely fast, especially if array2 grows.

Upvotes: 1

Zach Kemp
Zach Kemp

Reputation: 11904

This satisfies your example:

array2.select {|key,value| array1.include?(key) }

Upvotes: 5

Related Questions