2

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

4 Answers 4

5

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]]
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Please, never use sort for a keyed sort (i.e. never use sort when sort_by will do). Not only is it more readable, it is also more efficient.
@JörgWMittag My benchmarks show sort is about 2.5x faster than sort_by: gist.github.com/augustt198/b73aeab4bd76833c3d65. I can understand the readability though.
3
[[1, 2], [44, 1], [18395, 3]].sort_by(&:last).reverse

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.