# Sorting a list based on the length of each entry

Is there a way to sort an itemized list based on the length of each item? Something like

\begin{Itemize}
\item a
\item aaaaaa
\item aaaa
\item aaa
\item aaaaa
\item aa
\end{Itemize}


which results in

a
aa
aaa
aaaa
aaaaa
aaaaaa

-
what is you real use case? Do you have to use \item markup (which makes it harder as the items are not explicit arguments of anything, and what do you mean by "length" characters in the input or typeset length is W longer than .. or not? –  David Carlisle Feb 22 '13 at 0:01
Sorry for delay in replying. The answer you have provided in the following is precisely what I was looking for. –  Reza Feb 22 '13 at 17:01

This assumes you meant typeset length (and that all the items are single line)

\documentclass{article}

\def\Itemize{\vbox\bgroup
\let\item\ItemizeItem
\let\endItemizeItem\relax}

\def\ItemizeItem{%
\endItemizeItem
\let\endItemizeItem\xendItemizeItem
\setbox0\hbox\bgroup\strut\ignorespaces}

\def\endItemize{\endItemizeItem\egroup}

\def\xendItemizeItem{%
\unskip\egroup
\setbox4\vbox{}%
\loop
\unskip
\setbox2\lastbox
\ifdim\wd2>\wd0
\setbox4\vbox{\box2\unvbox4}%
\repeat
\nointerlineskip
\box2
\nointerlineskip
\box0
\unvbox4}

\begin{document}

\begin{Itemize}
\item a
\item aaaaaa
\item aaaa
\item aaa
\item aaaaa
\item aa
\end{Itemize}

\end{document}

-
Great technique! I'm doing a brain-internal right-click save! –  Sašo Živanović Feb 22 '13 at 14:19
Sorting items in a list can be very useful to avoid ugly lists. It is nice to have a list with entries sorted according to the number of characters they have. Of course, here the order of entries is not important. Until now, I had to sort the list entries manually which is tedious and time consuming. It will even be worse if at a later time you have to add new entries. David's solution is a breath of fresh air. –  Reza Feb 22 '13 at 16:55