2

I have an array with allowed values and an array with given values.

Howto merge two arrays with values from array2 that are in 1?

allowed_values => ["one", "two", "three"]
given_values => ["", "one", "five", "three", "seven"]

...

expected_values => ["one", "three"]

1 Answer 1

4

You want the array intersection, and you can obtain it via the & operator:

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
Sign up to request clarification or add additional context in comments.

2 Comments

Its php, but thanks for the tip on intersection. Found [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] from the ruby docs
Err, wow. I somehow just assumed PHP despite the obvious Ruby code. I can only attribute this to having been awake less than 10 minutes. Apologies and I'm glad I at least gave you "array intersection" to Google.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.