Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort one array based on another array using 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.

This question differs from the possible duplicates because it deals with presence of elements in the corresponding array and no hashes are present here.

like image 900
Donny Avatar asked Jul 09 '26 04:07

Donny


2 Answers

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 }
like image 145
Aleksei Matiushkin Avatar answered Jul 11 '26 16:07

Aleksei Matiushkin


I would start by checking what elements from B exist in A :

B & A

and then sort it:

(B & A).sort_by { |e| A.index(e) }
like image 20
radubogdan Avatar answered Jul 11 '26 16:07

radubogdan