如何按每个数组中的第二个值对数组进行排序?

时间:2022-10-20 11:45:50

I have the following array:

我有以下数组:

[[1, 2], [44, 1], [18395, 3]]

Which I obtained by using this code:

我使用此代码获得:

current_user.friends_products.where("units.primary_image_id IS NOT NULL").group_by{|u| u.creator_id}.map {|k,v| [k, v.length]}

I want to sort the array by the second value of each array from greatest to least. So, this is what I'm trying to achieve:

我想要对数组的第二个值进行排序,从最大到最小。这就是我想要达到的目标

[[18395, 3], [1, 2], [44, 1]]

4 个解决方案

#1


5  

Use #sort_by with the second element descending:

使用#sort_by,第二个元素降序:

x = [[1, 2], [44, 1], [18395, 3]]
x.sort_by { |a, b| -b }
#=> [[18395, 3], [1, 2], [44, 1]]

#2


3  

[[1, 2], [44, 1], [18395, 3]].sort_by(&:last).reverse

#3


2  

You can use this Array#sort block:

您可以使用这个数组#排序块:

[[1, 2], [44, 1], [18395, 3]].sort { |a, b| b[1] <=> a[1] }
# => [[18395, 3], [1, 2], [44, 1]]

#4


2  

arr =[[1, 2], [44, 1], [18395, 3]]
arr.sort_by{|x,y|y}.reverse
# => [[18395, 3], [1, 2], [44, 1]]

#1


5  

Use #sort_by with the second element descending:

使用#sort_by,第二个元素降序:

x = [[1, 2], [44, 1], [18395, 3]]
x.sort_by { |a, b| -b }
#=> [[18395, 3], [1, 2], [44, 1]]

#2


3  

[[1, 2], [44, 1], [18395, 3]].sort_by(&:last).reverse

#3


2  

You can use this Array#sort block:

您可以使用这个数组#排序块:

[[1, 2], [44, 1], [18395, 3]].sort { |a, b| b[1] <=> a[1] }
# => [[18395, 3], [1, 2], [44, 1]]

#4


2  

arr =[[1, 2], [44, 1], [18395, 3]]
arr.sort_by{|x,y|y}.reverse
# => [[18395, 3], [1, 2], [44, 1]]