# Sorting Lists of lists of arbitrary length

I'm trying to sort a list of lists. The sublists are defined in length, but the length of the list containing it varies.

A simplified set might be:

{{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}}

but it could be:

a={{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}}

Sorting on the last element is built-in using

SortBy[a,Last];

How do I sort on an arbitrary element? In the example, the second.

To sort by a specific element use a pure function with the number in question. For your case (the second element) just do:

SortBy[a, #[[2]] &]
{{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}}

You can also use Sort like this:

Sort[a, #1[[2]] < #2[[2]] &]
• worked beautifully, thanks! Commented Oct 8, 2014 at 5:54
• @RickR You're welcome. Glad I could help. Commented Oct 8, 2014 at 5:55

There is also ... Ordering

ClearAll[sortBy];
sortBy[list_, column_, ord_: Less] := list[[Ordering[list[[All, column]], All, ord]]]

Examples:

a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}};
sortBy[a, 2]
(* {{7,1,4},{1,2,3},{12,4,8},{3,5,6},{10,7,1}} *)

sortBy[a, 2, Greater]
(* {{10,7,1},{3,5,6},{12,4,8},{1,2,3},{7,1,4}} *)

Row[MatrixForm /@ (MapAt[Style[#, Red, Bold, 18] &,
sortBy[a, #], {{All, #}}] & /@ {1, 2, 3})]

Row[MatrixForm /@ (MapAt[Style[#, Red, Bold, 18] &,
sortBy[a, #, Greater], {{All, #}}] & /@ {1, 2, 3})]

• oh, that's pretty cool. thanks for sharing/enlightening! Commented Oct 8, 2014 at 6:53
• @RickR, my pleasure. Welcome to mma.se.
– kglr
Commented Oct 8, 2014 at 6:55

Operator form of SortBy

a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}};

a // SortBy[Last]

{{10, 7, 1}, {1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {12, 4, 8}}

SortBy[#[[2]] &] @ a

{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}}