0

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]]

2 Answers 2

5

This satisfies your example:

array2.select {|key,value| array1.include?(key) }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.