How to SortBy Last and in Reverse order?

I am looking at the two functions SortBy and ReverseSort.

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, Last]


{{2, 3, 1}, {2, 2}, {3, 1, 2}, {1, 2, 3}}

How do I sort this by the last element, but in the reverse order? I want to get this:

{{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}

• may be I am missing your question. Is this what you want? Reverse@SortBy[{{1,2,3},{2,3,1},{3,1,2},{2,2}},Last] which gives {{1,2,3},{3,1,2},{2,2},{2,3,1}} Commented Nov 5, 2017 at 18:21

If you don't care about the ordering of {3, 1, 2} and {2, 2}, do this:

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, Minus @* Last]
{{1, 2, 3}, {2, 2}, {3, 1, 2}, {2, 3, 1}}


Otherwise, add a second sorting criterion; e.g.

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus @* Last, Minus @* Length}]
{{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}


or just wrap the sorting criterion in a list (per Alan):

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus @* Last}]
{{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}

• I think SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus@*Last}] will ensure a stable sort.
– Alan
Commented Nov 5, 2017 at 21:08
• Ah, right. Let me add that note. Commented Nov 5, 2017 at 21:10

Using:

l = {{2, 3, 1}, {2, 2}, {3, 1, 2}, {1, 2, 3}};


One option, just using Sort:

Sort[l, Last[#2] < Last[#1] &]


Another option, using SortBy and Reverse:

Reverse@SortBy[l, Last]


I'm not completely sure about ReverseSort (my version of Mathematica does not have it), but I imagine something like this would be at least a start (not too sure about "tie" cases, or how concerned you are with them):

ReverseSort[l, Last[#1] < Last[#2] &]


Not an expert on this, so anyone should feel free to correct me if I'm wrong.

• I'd expect SortBy to be considerably faster than Sort with a custom comparison function (because each custom comparison requires a Mathematica evaluation) Commented Nov 5, 2017 at 21:18