Mathematica > Core Language > List Manipulation > Rearranging & Restructuring Lists >
Mathematica > Data Manipulation > Handling Arrays of Data > Rearranging & Restructuring Lists >

SortBy

Updated In 7 Graphic
SortBy[list, f]
sorts the elements of list in the order defined by applying f to each of them.
  • SortBy[{e1, e2, e3, ...}, f] sorts the ei so that the f[ei] lie in canonical order.
  • If some of the f[ei] are the same, then the canonical order of the corresponding ei is used.
  • SortBy[list, {f1, f2, ...}] breaks ties by successively using the values obtained from the fi.
  • SortBy uses the canonical ordering described in the notes for Sort.
  • SortBy can be used on expressions with any head, not only List.
Sort a list of lists by the last element of each sublist:
In[1]:=
Click for copyable input
Out[1]=
Sort by the total of each sublist:
In[2]:=
Click for copyable input
Out[2]=
 
Sort a list of integers by their values modulo 3:
In[1]:=
Click for copyable input
Out[1]=
New in 6 | Last modified in 7
Ask a question about this page  |  Suggest an improvement  |  Leave a message for the team