RoboCode RoboCode - 5 months ago 34
Ruby Question

Sorting One Array based on another array in ruby

There are two arrays

A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
B = [3, 4, 1, 5, 2, 6]


I want to sort
B
in a way that for all the elements of
B
that exists in
A
, sort the elements in the order that is in array
A
.

The desired sorted resulted would be

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


I have tried to do
B = B.sort_by { |x| A.index }
but it does not work.

Answer

It perfectly works:

▶ A = [1,3,2,6,4,5,7,8,9,10]
▶ B = [3,4,1,5,2,6]
▶ B.sort_by &A.method(:index)
#⇒ [1, 3, 2, 6, 4, 5]

If there could be elements in B that are not present in A, use this:

▶ B.sort_by { |e| A.index(e) || Float::INFINITY }
Comments