[英]How can I sort this array of arrays by the second value in each array?
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]]
[[1, 2], [44, 1], [18395, 3]].sort_by(&:last).reverse
You can use this Array#sort
block: 您可以使用此
Array#sort
块:
[[1, 2], [44, 1], [18395, 3]].sort { |a, b| b[1] <=> a[1] }
# => [[18395, 3], [1, 2], [44, 1]]
arr =[[1, 2], [44, 1], [18395, 3]]
arr.sort_by{|x,y|y}.reverse
# => [[18395, 3], [1, 2], [44, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.