Reputation: 1024
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]]
Upvotes: 2
Views: 316
Reputation: 258138
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]]
Upvotes: 5
Reputation: 16506
arr =[[1, 2], [44, 1], [18395, 3]]
arr.sort_by{|x,y|y}.reverse
# => [[18395, 3], [1, 2], [44, 1]]
Upvotes: 2
Reputation: 12558
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]]
Upvotes: 3