In Ruby, how do you sort one multidimensional array with another multidimensional array?

Let's say I have an array: a = [[1,2,3], [4,5]] and I have another array: b = [[2.5.1.5.3.5], [1.5.2.5]]

I need to sort 'a' relative to 'b'. that is, the output should be = [[3,1,2], [5,4]]

I tried, but my code seemed very long. It would be great if you could help me. Thanks!

+4
source share
2 answers

This gives your sample output for sample input, so hopefully this is what you want (it sorts the values ​​of each subarray in the first array by the value in the same position in the corresponding subarray of the second array, in descending order):

class Array def sort_by_other_array(arr) zip(arr).sort_by {|x,y| y}.map {|x,y| x} end end a=[[1,2,3],[4,5]] b=[[2.5,1.5,3.5],[1.5,2.5]] a.zip(b).map {|x,y| x.sort_by_other_array(y).reverse} #=> [[3, 1, 2], [5, 4]] 
+3
source

Next time it would be nice to post your code as well as clarify the context.

Here you can get the desired results.

 a.zip(b).map do |values, sort_values| sort_values.zip(values).sort.reverse_each.map{|sort, value| value} end 
+1
source

Source: https://habr.com/ru/post/1306040/


All Articles