Sort by more than one element?

Is it possible to sort an array by more than one column?

julia> x
4-element Array{Array{Int64,1},1}:
 [1,1,1,5,1]
 [2,1,3,2,1]
 [3,1,1,1,5]
 [1,3,2,4,1]

julia> sort(x, by = x -> x[1]) # sort by first element, yes
4-element Array{Array{Int64,1},1}:
 [1,1,1,5,1]
 [1,3,2,4,1]
 [2,1,3,2,1]
 [3,1,1,1,5]

Now I’m looking for a way to sort by element 1, then, say, by element 4:

 [1,3,2,4,1]
 [1,1,1,5,1]
 [2,1,3,2,1]
 [3,1,1,1,5]

sortrows() looks promising, but won’t do it here. Is this a job for DataTables?

Specify lt?

A = [[1,1,1,5,1],
     [2,1,3,2,1],
     [3,1,1,1,5],
     [1,3,2,4,1]]

custom_lt(x, y) = x[1] == y[1] ? x[4] < y[4] : x[1] < y[1]

sort(A, lt=custom_lt)
1 Like

@yuyichao @pfitzseb Of course! Thanks! For some reason I didn’t think of that…

Create a tuple that sorts as desired.

sort(x, by=x->(x[1],x[4]))

5 Likes

Even better! Thanks.