Sri
Sri

Reputation: 39

ruby multidimension array sorting

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

Upvotes: 0

Views: 80

Answers (2)

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79562

Why not take the simple and clear route:

arr.sort.reverse
# => [[67, 2], [67, 1], [44, 5], [30, 2], [24, 4]]

Upvotes: 4

tokland
tokland

Reputation: 67850

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

Upvotes: 3

Related Questions