# 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.

SortBy[f]

represents an operator form of SortBy that can be applied to an expression.

# 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 all close all

## Basic Examples(4)

Sort a list of lists by the last element of each sublist:

 In:= Out= Sort by the total of each sublist:

 In:= Out= Sort a list of integers by their values modulo 3:

 In:= Out= Sort elements of an Association by their values modulo 3:

 In:= Out= Use SortBy as an operator form:

 In:= Out= ## Properties & Relations(3)

Introduced in 2007
(6.0)
|
Updated in 2019
(12.0)