igavriil
igavriil

Reputation: 1021

Sort array by other array

I have two arrays:

a = [ 1, 0, 2, 1, 0]
b = ['a', 'b', 'c', 'd', 'e']

I want to order the b array according to a's elements values. I can make this by merging the two arrays into a Hash and the order by key:

h = Hash[b.zip a]
=> {"a"=>1, "b"=>0, "c"=>2, "d"=>1, "e"=>0}

h2 = Hash[h.sort_by{|k, v| v}]
=> {"b"=>0, "e"=>0, "a"=>1, "d"=>1, "c"=>2}

array = h2.keys
=> ["b", "e", "a", "d", "c"]

Where there is a tie the order may be chosen arbitrary.

Is there a way (maybe more compact), I can achieve this without using the hash.

Upvotes: 2

Views: 114

Answers (2)

steenslag
steenslag

Reputation: 80065

a = [ 1, 0, 2, 1, 0]
b = ['a', 'b', 'c', 'd', 'e']

p b.sort_by.each_with_index{|el,i| a[i]}
# => ["b", "e", "a", "d", "c"]

Upvotes: 2

Doguita
Doguita

Reputation: 15703

a.zip(b).sort.map(&:last)

In parts:

p a.zip(b) # => [[1, "a"], [0, "b"], [2, "c"], [1, "d"], [0, "e"]] 
p a.zip(b).sort # => [[0, "b"], [0, "e"], [1, "a"], [1, "d"], [2, "c"]] 
p a.zip(b).sort.map(&:last) # => ["b", "e", "a", "d", "c"]

Upvotes: 3

Related Questions