Snubber
Snubber

Reputation: 1024

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]]

Upvotes: 2

Views: 316

Answers (4)

Mark Rushakoff
Mark Rushakoff

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

shivam
shivam

Reputation: 16506

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

Upvotes: 2

sawa
sawa

Reputation: 168081

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

Upvotes: 3

August
August

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

Related Questions