0

I have an array like this

arr = [[24,4], [44,5],[67,1], [30, 2], [67, 2]]

If i am using arr.sort{|a,b| b[0]<=>a[0]} i get this result

[[67,1], [67, 2], [44,5], [30, 2], [24,4]] -  #[value, id]

How to sort again the array to achieve this result

[[67,2], [67, 1], [44,5], [30, 2], [24,4]] -  #[value, id]

If there are same values, then the sort should happen on id descending .

thanks

2 Answers 2

4

Why not take the simple and clear route:

arr.sort.reverse
# => [[67, 2], [67, 1], [44, 5], [30, 2], [24, 4]]
Sign up to request clarification or add additional context in comments.

Comments

3

It's better to use Enumerable#sort_by:

arr = [[24,4], [44,5],[67,1], [30, 2], [67, 2]]
arr.sort_by { |x, y| [-x, -y] }
#=> [[67, 2], [67, 1], [44, 5], [30, 2], [24, 4]]

2 Comments

thanks tokland, is there any method to get results only for value > 50 from arr ?
use select. You should check the docs of Array and Enumerable.

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.