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]]
Use #sort_by with the second element descending:
x = [[1, 2], [44, 1], [18395, 3]]
x.sort_by { |a, b| -b }
#=> [[18395, 3], [1, 2], [44, 1]]
[[1, 2], [44, 1], [18395, 3]].sort_by(&:last).reverse
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]]
arr =[[1, 2], [44, 1], [18395, 3]]
arr.sort_by{|x,y|y}.reverse
# => [[18395, 3], [1, 2], [44, 1]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.