# Sort the nested list by the sublist content; sublists of different lengths

I would like to write the function NewSort function that sorts a list of sorted sublists, basing first on the canonical ordering of subsequent sublist elements. In case of the tie, the shorter sublist should be first.

Example 1:

NewSort[{{1,2,4},{3,4},{1,3}}]


Should give

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


Example 2:

NewSort[{{1,2,3},{1,2},{1}}]


Should give

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


Edited version: this is a clean-up by taking into consideration the added example provided in the comments section by the author of the OP.

I am suggesting the following function:

foo[l_List] :=
InternalDeleteTrailingZeros /@
SortBy[#, Table[#[[xx]], {xx, 1, Min[Dimensions /@ l]}] &] &@


Now, we define the four lists; two from the OP, the one I had provided as example 3 and the one in the comments by the author of the OP.

list1 = {{1, 2, 4}, {3, 4}, {1, 3}};
list2 = {{1, 2, 3}, {1, 2}, {1}};
list3 = {{1, 2, 4}, {3, 4}, {4, 5}, {1, 3, 7, 8}, {1, 3}};
list4 = {{1}, {1, 2, 4}, {1, 2, 3, 5}};


We act with the function

foo[list1]
foo[list2]
foo[list3]
foo[list4]


Edit: thanks to the comment by @E. Chan-López, there's the shorter version:

foo[l_List] :=
DeleteCases[#, 0] & /@ SortBy[#, Min[Length /@ l] &] &@PadRight@l

• Although this solves the problem, it is a loop-based solution. Is it possible to find something more efficient? Feb 21 at 9:54
• @wedelfach by loop, you mean that I used a Table in SortBy?
– bmf
Feb 21 at 9:55
• Yes, if I understood Your solution correctly, it run over every sublist on the parent list. Feb 21 at 10:06
• A bit shorter: DeleteCases[#, 0] & /@ SortBy[#, Min[Length /@ l] &] &@PadRight@l` Feb 21 at 16:43
• @E.Chan-López cheers mate. I updated the answer. not sure why I like undocumented stuff so much :-)
– bmf
Feb 22 at 1:29