Array sort by two values

Let's pretend that

an_array = [[2, 3], [1, 4], [1, 3], [2, 1], [1, 2]] 

I want to sort this array by the first value of each internal array, and then by the second (so the sorted array should look like this: [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3]] )

What is the most readable way to do this?

+7
ruby
source share
3 answers

This is the default behavior for sorting arrays (see the definition of the Array # <=> method for proof). You should just be able to:

  an_array.sort 
+13
source share

If you want custom behavior, sort_by (ruby 1.8.7 +)

eg. sort by second element and then by first

 a.sort_by {|e| [e[1], e[0]]} # => [[2, 1], [1, 2], [1, 3], [2, 3], [1, 4]] 

or sort by first element ascending and then descending second element

 a.sort_by {|e| [e[0], -e[1]]} # => [[1, 4], [1, 3], [1, 2], [2, 3], [2, 1]] 
+8
source share

an_array.sort

+1
source share

All Articles