linkyndy
linkyndy

Reputation: 17910

Pop matching elements from array, then push them back

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?

Upvotes: 0

Views: 78

Answers (2)

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

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]

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122403

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.

Upvotes: 7

Related Questions