0

Say I have an array: [1, 2, 3, 4, 5].

Given another array ([2, 4], for example), I would like to have a new array (or the initial array modified, doesn't matter) that looks like: [1, 3, 5, 2, 4]. So selected elements are moved to the end of the array.

Pushing the elements back is quite straight-forward, but how do I pop specific elements from an array?

2
  • Given another array [4,2], should the result be [1, 3, 5, 2, 4] or [1, 3, 5, 4, 2], or either? Commented Jan 20, 2015 at 20:33
  • The elements should best be pushed in the same order Commented Jan 21, 2015 at 9:46

2 Answers 2

7
a = [1, 2, 3, 4, 5]
b = [2, 4]

(a - b) + (b & a)
#=> [1, 3, 5, 2, 4]

a - b is the elements in a but not in b, while b & a is the elements that are common in both arrays. There goes your expected result.

Sign up to request clarification or add additional context in comments.

4 Comments

I would (a-b)+(b&a) to save the order of elements in the second array. Though it depends on what OP desired.
If the elements of a are not unique, the result might not be what is expected.
Why not just (a-b) + b
I suggest you make b = [4,2], and then (a-b) + b #=> [1, 3, 5, 4, 2] or (a-b) + (a&b) #=> [1, 3, 5, 2, 4] , depending on the desired order of the last two elements.
1

In case if elements in a are not uniq (as mentioned by eugen) and it's important to remove only one element from b you could do something like:

a = [1, 2, 3, 2, 4, 5, 4, 2]
b = [2, 4, 7]
p (b&a).unshift(a.map{|el|
    b.include?(el) ? begin b = b -[el]; nil end : el
  }.compact).flatten

#=> [1, 3, 2, 5, 4, 2, 2, 4]

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.