0

I am looking for a proper way to sort by ascending or descending a complex array.

arr = [[100, 200, 300], [100, 250, 600], [50, 10, 1030]]

I would like to sort this array based on the target value [value, value, target_value]

I have my own way to do this but it seems ugly and slow.

Do we have a proper way to do this in ruby?

Thanks in advance.

Joel
  • 4,503
  • 1
  • 27
  • 41
jonjon
  • 3
  • 2

3 Answers3

4

Or even shorter like this:

arr.sort_by(&:last)

If you need it in descend order:

arr.sort_by(&:last).reverse

To do the sorting and reversing in two steps seems laborious, but it is actually faster than the sort {} syntax.

spickermann
  • 100,941
  • 9
  • 101
  • 131
3
[[100, 200, 300], [100, 250, 600], [50, 10, 1030]].sort_by{|x| x[2]}
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
1

Here's a way to do it more explicitly:

arr.sort { |a, b| a[2] <=> b[2] }

For a descending sort, just reverse the order:

arr.sort { |a, b| b[2] <=> a[2] }
dwenzel
  • 1,404
  • 9
  • 15