Reputation: 12495
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
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
Reputation: 11904
This satisfies your example:
array2.select {|key,value| array1.include?(key) }
Upvotes: 5