Sort by more than one element?

question

#1

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?


#2

Specify lt?


#3
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)

#4

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


#5

Create a tuple that sorts as desired.

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


#6

Even better! Thanks.