# Nested sorting of lists

I have the following list representing a custom set of cards:

Each card is represented by a list of two elements, like this: {heart,9}

Using the code:

    Subsets[deck, {5}]


I have received a list of all the possible hands of 5 cards you can have, which totals to 1 712 304 possible hands.

I now have a list containing 1 712 304 lists of 5 cards, which are also lists of 2 elements. I now want to sort each hand separately by the number on the cards, ignoring their colors. The order of the hands does not matter, only that each hand is sorted by number internally.

I tried the following code:

    Sort[hands, #1[[2]] < #2[[2]] &]


But that did not work out.

• Usually it is helpful, if the input data is given as a copiable code. Then we can test our solution using the same input easily. – Johu Sep 20 '18 at 11:19

In[1]:=
deck = Reverse[{{"foo", 9}, {"bar", 10}, {"car", 11}}]
hands = Subsets[deck, {2}]
Table[SortBy[hand, Last], {hand, hands}]

Out[1]= {{"car", 11}, {"bar", 10}, {"foo", 9}}

Out[2]= {{{"car", 11}, {"bar", 10}}, {{"car", 11}, {"foo", 9}}, {{"bar", 10}, {"foo", 9}}}

Out[3]= {{{"bar", 10}, {"car", 11}}, {{"foo", 9}, {"car", 11}}, {{"foo", 9}, {"bar", 10}}}


I prefer Table[Sort[hand, Last], {hand, hands}] to SortBy[Last]/@hands as the former leaves more readable and verbose code.

Note, that I used SortBy[hand, Last], which does the same as Sort[hands, #1[[-1]] < #2[[-1]] &], but is easier to read. I am a big fan of semantic code which is basically somethign you could just read out loud and is self explaining.

To order hands by rank you can use

SortBy[#[[2]] &] /@ hands


This constructs a sorting function that sorts by the second element of an expression and then Maps it over all hands.