I have two arrays. The first array contains the sort order. The second array contains an arbitrary number of elements.
I have the property that all elements (value-wise) from the second array are guaranteed to be in the first array, and I am only working with numbers.
A = [1,3,4,4,4,5,2,1,1,1,3,3]
Order = [3,1,2,4,5]
When I sort A
, I would like the elements to appear in the order specified by Order
:
[3, 3, 3, 1, 1, 1, 1, 2, 4, 4, 4, 5]
Note that duplicates are fair game. The elements in A should not be altered, only re-ordered. How can I do this?
>> source = [1,3,4,4,4,5,2,1,1,1,3,3]
=> [1, 3, 4, 4, 4, 5, 2, 1, 1, 1, 3, 3]
>> target = [3,1,2,4,5]
=> [3, 1, 2, 4, 5]
>> source.sort_by { |i| target.index(i) }
=> [3, 3, 3, 1, 1, 1, 1, 2, 4, 4, 4, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With