SortBy
SortBy[list,f]
sorts the elements of list in the order defined by applying f to each of them.
SortBy[list,{f1,f2,…}]
breaks ties by successively using the values obtained from the fi.
SortBy[list,f,p]
sorts the elements of list using the function p to compare the results of applying f to each element.
Details
- 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[{e1,e2,e3,…},f,p] sorts the ei so that the f[ei] are sorted according to the ordering function p: ei will be sorted before ej if p[f[ei],f[ej]] is 1 or True.
- SortBy uses the canonical ordering described in the notes for Sort.
- SortBy can be used on expressions with any head, not only List.
- SortBy[f][list] is equivalent to SortBy[list,f].
Examples
open allclose allBasic Examples (4)
Sort a list of lists by the last element of each sublist:
Sort by the total of each sublist:
Sort a list of integers by their values modulo 3:
Sort elements of an Association by their values modulo 3:
Use SortBy as an operator form:
Scope (7)
The default order ranks these symbolically:
Sort by absolute numerical value:
Sort a list of vectors by their norm:
Their norms are sorted following canonical order, but not numerical order:
Explicitly request sorting of norms by numerical order:
Sort complex numbers by their modulus using numerical order:
Generalizations & Extensions (1)
SortBy can be used on expressions with any head:
Applications (3)
Show the top 10 countries according to different criteria:
Sort the first 10 countries in alphabetical order by population:
Sort the first 10 countries in alphabetical order by area:
Sort mathematically equivalent expressions by different criteria:
Sort by LeafCount:
Sort by size of error for numerical evaluation with machine numbers at :
Properties & Relations (4)
Sort[list] is equivalent to SortBy[list,Identity]:
SortBy[e,f] is equivalent to Sort[{f[#],#}&/@e][[All,-1]]:
ReverseSortBy uses reverse canonical ordering:
The result of ReverseSortBy[list,fs] is not always Reverse[SortBy[list,fs]]:
SortBy[list,f] is equivalent to list[[OrderingBy[list,f]]]:
Text
Wolfram Research (2007), SortBy, Wolfram Language function, https://reference.wolfram.com/language/ref/SortBy.html (updated 2019).
CMS
Wolfram Language. 2007. "SortBy." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2019. https://reference.wolfram.com/language/ref/SortBy.html.
APA
Wolfram Language. (2007). SortBy. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/SortBy.html