---
title: "MaximalBy"
language: "en"
type: "Symbol"
summary: "MaximalBy[data, f] returns a list of the elements ei of data for which the value of f[ei] is maximal. MaximalBy[data, f, n] returns a list of the elements ei of data corresponding to the n largest f[ei]. MaximalBy[data, f, n, p] uses the ordering function p for sorting. MaximalBy[f] represents an operator form of MaximalBy that can be applied to an expression."
keywords: 
- max
- maximal
- largest
- sorted
- top
- biggest
canonical_url: "https://reference.wolfram.com/language/ref/MaximalBy.html"
source: "Wolfram Language Documentation"
related_guides: 
  - 
    title: "Math & Counting Operations on Lists"
    link: "https://reference.wolfram.com/language/guide/MathematicalAndCountingOperationsOnLists.en.md"
  - 
    title: "Functional Programming"
    link: "https://reference.wolfram.com/language/guide/FunctionalProgramming.en.md"
  - 
    title: "Elements of Lists"
    link: "https://reference.wolfram.com/language/guide/ElementsOfLists.en.md"
  - 
    title: "Function Composition & Operator Forms"
    link: "https://reference.wolfram.com/language/guide/FunctionCompositionAndOperatorForms.en.md"
  - 
    title: "Tabular Objects"
    link: "https://reference.wolfram.com/language/guide/TabularObjects.en.md"
related_functions: 
  - 
    title: "MinimalBy"
    link: "https://reference.wolfram.com/language/ref/MinimalBy.en.md"
  - 
    title: "Max"
    link: "https://reference.wolfram.com/language/ref/Max.en.md"
  - 
    title: "TakeLargest"
    link: "https://reference.wolfram.com/language/ref/TakeLargest.en.md"
  - 
    title: "TakeLargestBy"
    link: "https://reference.wolfram.com/language/ref/TakeLargestBy.en.md"
  - 
    title: "FindMaximum"
    link: "https://reference.wolfram.com/language/ref/FindMaximum.en.md"
  - 
    title: "Maximize"
    link: "https://reference.wolfram.com/language/ref/Maximize.en.md"
  - 
    title: "RankedMax"
    link: "https://reference.wolfram.com/language/ref/RankedMax.en.md"
  - 
    title: "ReverseSortBy"
    link: "https://reference.wolfram.com/language/ref/ReverseSortBy.en.md"
  - 
    title: "Ordering"
    link: "https://reference.wolfram.com/language/ref/Ordering.en.md"
---
# MaximalBy

MaximalBy[data, f] returns a list of the elements ei of data for which the value of f[ei] is maximal.

MaximalBy[data, f, n] returns a list of the elements ei of data corresponding to the n largest f[ei].

MaximalBy[data, f, n, p] uses the ordering function p for sorting.

MaximalBy[f] represents an operator form of MaximalBy that can be applied to an expression.

## Details

* By default, values of ``f[ei]`` are compared using ``Order``, the same canonical order as in ``Sort``.

* ``MaximalBy[data, f]`` returns the list of maximal elements ``ei`` of data in the order they appear in the input.

* ``MaximalBy[data, f, n]`` returns the ``ei`` sorted in the order of decreasing ``f[ei]``, with those having the same value of ``f[ei]`` being taken in the order they appear in ``data``.

* The ``data`` can have the following forms:

|                  |                                                           |
| ---------------- | --------------------------------------------------------- |
| {e1, e2, …}      | list of values, including numbers, quantities, dates, ... |
| Association[…]   | association of values  »                                  |
| QuantityArray[…] | quantity array or other structured array  »               |
| Tabular[…]       | type-consistent tabular data  »                           |
| TabularColumn[…] | type-consistent column data  »                            |
| Dataset[…]       | general hierarchical data  »                              |

* For tabular data ``tab``, ``MaximalBy[tab, f, …]`` applies the function ``f`` to individual rows of ``tab``, with the row being an association ``<|col1 -> val1, …|>`` if ``tab`` has column keys or a list ``{val1, …}`` if ``tab`` does not have column keys.

* ``MaximalBy[data, f, UpTo[n]]`` gives ``n`` elements, or as many as are available.  »

* ``MaximalBy[f][data]`` is equivalent to ``MaximalBy[data, f]``.  »

## Examples (21)

### Basic Examples (4)

Find the maximal element by its last part:

```wl
In[1]:= MaximalBy[{{a, 1}, {b, 1}, {a, 2}, {d, 1}, {b, 3}}, Last]

Out[1]= {{b, 3}}
```

Do the same using the operator form of ``MaximalBy`` :

```wl
In[2]:= MaximalBy[Last][{{a, 1}, {b, 1}, {a, 2}, {d, 1}, {b, 3}}]

Out[2]= {{b, 3}}
```

---

All maximal elements are returned, in order of appearance:

```wl
In[1]:= MaximalBy[{{a, 1}, {b, 1}, {b, 3}, {d, 2}, {a, 3}}, Last]

Out[1]= {{b, 3}, {a, 3}}
```

---

Obtain the first three maximal elements:

```wl
In[1]:= MaximalBy[{{a, 1}, {b, 1}, {b, 3}, {d, 2}, {a, 3}}, Last, 3]

Out[1]= {{b, 3}, {a, 3}, {d, 2}}
```

---

Prune an association to its maximal values:

```wl
In[1]:= MaximalBy[<|"a" -> {1, 1}, "b" -> {2, 3}, "c" -> {4, 2}, "d" -> {1, 3}|>, Last]

Out[1]= <|"b" -> {2, 3}, "d" -> {1, 3}|>
```

### Scope (10)

Obtain the first four maximal elements or as many as are available:

```wl
In[1]:= MaximalBy[{{a, 1}, {b, 1}, {b, 3}}, First, UpTo[4]]

Out[1]= {{b, 1}, {b, 3}, {a, 1}}
```

---

``MaximalBy`` works with symbolic expressions, using canonical ``Order`` by default:

```wl
In[1]:= MaximalBy[{{a, 1}, {b, 1}, {b, 3}, {d, 2}, {a, 3}}, First]

Out[1]= {{d, 2}}
```

---

Find maximal element in a list of comparable quantities with various units:

```wl
In[1]:= data = {Quantity[3, "Feet"], Quantity[9, "Inches"], Quantity[1, "Meters"]};
```

Comparing by ``QuantityMagnitude`` loses the unit information:

```wl
In[2]:= MaximalBy[data, QuantityMagnitude]

Out[2]= {Quantity[9, "Inches"]}
```

Find numerically largest element:

```wl
In[3]:= MaximalBy[data, NumericalSort]

Out[3]= {Quantity[1, "Meters"]}
```

---

``MaximalBy`` works on ``QuantityArray`` :

```wl
In[1]:= data = QuantityArray[RandomReal[1, {6, 2}], {"Meters", "Seconds"}]

Out[1]=
QuantityArray[StructuredArray`StructuredData[{6, 2}, 
  {{{0.7489667862288363, 0.26567821321815255}, {0.039507272184289066, 0.5550495449105484}, 
    {0.5109766275101033, 0.9809601236210443}, {0.9891502342591956, 0.8529257187102117}, 
    {0.39864612610019723, 0.5632234989543645}, {0.6610493803435287, 0.08795461712485708}}, 
   {"Meters", "Seconds"}, {{1}, {2}}}]]

In[2]:= MaximalBy[data, Last]//Normal

Out[2]= {{Quantity[0.5109766275101033, "Meters"], Quantity[0.9809601236210443, "Seconds"]}}
```

---

``MaximalBy`` will order dates according to canonical order by default:

```wl
In[1]:= dates = {DateObject[{2024, 9, 12}], "12 Sept 2022", {2023, 9, 12}};

In[2]:= MaximalBy[dates, Identity]

Out[2]= {{2023, 9, 12}}
```

Convert the dates to absolute times to sort them numerically:

```wl
In[3]:= MaximalBy[dates, AbsoluteTime]

Out[3]= {DateObject[{2024, 9, 12}, "Day"]}
```

Equivalently, convert the dates to ``DateObject`` form and use ``NumericalOrder`` instead of ``Order`` :

```wl
In[4]:= MaximalBy[dates, DateObject, 1, NumericalOrder]

Out[4]= {DateObject[{2024, 9, 12}, "Day"]}
```

---

Take the letters of the Polish alphabet:

```wl
In[1]:= letters = Entity["Alphabet", "Polish::7949q"]["CommonAlphabet"]

Out[1]= {"a", "ą", "b", "c", "ć", "d", "e", "ę", "f", "g", "h", "i", "j", "k", "l", "ł", "m", "n", "ń", "o", "ó", "p", "r", "s", "ś", "t", "u", "w", "y", "z", "ź", "ż"}
```

Transliterate them to the Hiragana script:

```wl
In[2]:= hiragana = Transliterate[letters, "Polish" -> "Hiragana"]

Out[2]= {"あ", "あ̨", "ぶ", "く", "く́", "で", "え", "え̨", "ふ", "ぐ", "へ", "い", "じ", "く", "る", "ł", "む", "ん", "ん́", "お", "お́", "ぷ", "る", "す", "す́", "て", "う", "う", "い", "ず", "ず́", "ず̇"}
```

These are the five largest Polish letters according to canonical order:

```wl
In[3]:= MaximalBy[letters, Identity, 5]

Out[3]= {"z", "y", "w", "u", "t"}
```

These are the five largest Polish letters according to the rules of the Polish alphabet:

```wl
In[4]:= MaximalBy[letters, Identity, 5, AlphabeticOrder["Polish"]]

Out[4]= {"ż", "ź", "z", "y", "w"}
```

These are the five largest Polish letters according to canonical order of their Hiragana transliteration:

```wl
In[5]:= MaximalBy[letters, Transliterate[#, "Polish" -> "Hiragana"]&, 5]

Out[5]= {"ł", "ń", "ż", "ź", "ś"}
```

These are the five largest Polish letters according to alphabetic order in Japanese of their transliteration:

```wl
In[6]:= MaximalBy[letters, Transliterate[#, "Polish" -> "Hiragana"]&, 5, AlphabeticOrder["Japanese"]]

Out[6]= {"ń", "n", "l", "r", "m"}
```

---

Construct a ``TabularColumn`` object with 100 words:

```wl
In[1]:= col = TabularColumn[RandomWord[100]]

Out[1]=
TabularColumn[Association["Data" -> {{3, CompressedData["«311»"], "unshackledcylindricaluneasema\
verickellipsoidreverepricebelaystalematedmannertransposedeulogisticabscissatumulusunspecifiedhydrau\
licsintersectfoolhardinessshamrockknownfloodlight ... ateintermediatelyteasinghatefulnessmodulatedprofusejustifiableaminosweptbacklatti\
cesecurebuckskinconduceendorphintiddlygooeyburgundybargaincharitablesilenceubiquityinsecticideteapo\
tviewpointbuzzwordspy"}, {}, None}, "ElementType" -> "String"]]
```

Select the five longest words:

```wl
In[2]:= MaximalBy[col, StringLength, 5]

Out[2]=
TabularColumn[Association["Data" -> {{3, {0, 15, 30, 44, 58, 71}, 
     "procrastinationself-protectionprescriptivismintermediatelyfoolhardiness"}, {}, None}, 
  "ElementType" -> "String"]]
```

Normalize the result to a list:

```wl
In[3]:= Normal[%]

Out[3]= {"procrastination", "self-protection", "prescriptivism", "intermediately", "foolhardiness"}
```

---

Find the four rows in a ``Tabular`` object with largest values in a given column:

```wl
In[1]:=
data = {{8, 13, 18, 8, 14, 13, 18, 27}, {16.1, 29.2, 23.8, 14.7, 30.1, 27.5, 35.1, 36.2}};
tab = ToTabular[data, "Columns", {"size", "length"}]

Out[1]=
Tabular[Association["RawSchema" -> Association["ColumnProperties" -> 
     Association["size" -> Association["ElementType" -> "Integer64"], 
      "length" -> Association["ElementType" -> "Real64"]], "KeyColumns" -> None, 
    "Backend" -> "Wolfram ... ta" -> {{8, 13, 18, 8, 14, 13, 18, 27}, {}, None}, 
          "ElementType" -> "Integer64"]], TabularColumn[Association[
          "Data" -> {{16.1, 29.2, 23.8, 14.7, 30.1, 27.5, 35.1, 36.2}, {}, None}, 
          "ElementType" -> "Real64"]]}}]]]]

In[2]:= MaximalBy[tab, "length", 4]

Out[2]=
Tabular[Association["RawSchema" -> Association["ColumnProperties" -> 
     Association["size" -> Association["ElementType" -> "Integer64"], 
      "length" -> Association["ElementType" -> "Real64"]], "KeyColumns" -> None, 
    "Backend" -> "Wolfram ... umnTable", 
      {{TabularColumn[Association["Data" -> {{27, 18, 14, 13}, {}, None}, 
          "ElementType" -> "Integer64"]], TabularColumn[Association[
          "Data" -> {{36.2, 35.1, 30.1, 29.2}, {}, None}, "ElementType" -> "Real64"]]}}]]]]
```

Use general functional notation instead of the column name:

```wl
In[3]:= MaximalBy[tab, #length&, 4]

Out[3]=
Tabular[Association["RawSchema" -> Association["ColumnProperties" -> 
     Association["size" -> Association["ElementType" -> "Integer64"], 
      "length" -> Association["ElementType" -> "Real64"]], "KeyColumns" -> None, 
    "Backend" -> "Wolfram ... umnTable", 
      {{TabularColumn[Association["Data" -> {{27, 18, 14, 13}, {}, None}, 
          "ElementType" -> "Integer64"]], TabularColumn[Association[
          "Data" -> {{36.2, 35.1, 30.1, 29.2}, {}, None}, "ElementType" -> "Real64"]]}}]]]]
```

Use function of both columns:

```wl
In[4]:= MaximalBy[tab, (#length - #size)&, 4]

Out[4]=
Tabular[Association["RawSchema" -> Association["ColumnProperties" -> 
     Association["size" -> Association["ElementType" -> "Integer64"], 
      "length" -> Association["ElementType" -> "Real64"]], "KeyColumns" -> None, 
    "Backend" -> "Wolfram ... umnTable", 
      {{TabularColumn[Association["Data" -> {{18, 13, 14, 13}, {}, None}, 
          "ElementType" -> "Integer64"]], TabularColumn[Association[
          "Data" -> {{35.1, 29.2, 30.1, 27.5}, {}, None}, "ElementType" -> "Real64"]]}}]]]]
```

---

Take a dataset of the solar system planets:

```wl
In[1]:= dataset = Dataset[ExampleData[{"Dataset", "Planets"}], MaxItems -> 4]

Out[1]=
Dataset[Association["Mercury" -> Association["Mass" -> Quantity[3.30104`6.*^23, "Kilograms"], 
    "Radius" -> Quantity[2439.7`5., "Kilometers"], "Moons" -> Association[]], 
  "Venus" -> Association["Mass" -> Quantity[4.867320000000000000000001`6.* ... "]], 
      "Psamathe" -> Association["Mass" -> Missing["NotAvailable"], 
        "Radius" -> Quantity[20.`2., "Kilometers"]], 
      "Neso" -> Association["Mass" -> Missing["NotAvailable"], 
        "Radius" -> Quantity[30.`2., "Kilometers"]]]]]]
```

Find the three planets with the maximal number of moons:

```wl
In[2]:= MaximalBy[dataset, Length[#Moons]&, 3]//Keys

Out[2]= Dataset[{"Jupiter", "Saturn", "Uranus"}]
```

---

When there are common values of ``f[ei]`` for different elements ``ei``, the original order will be kept:

```wl
In[1]:= list = Range[-5, 5]

Out[1]= {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}

In[2]:= MaximalBy[list, Abs, 4]

Out[2]= {-5, 5, -4, 4}

In[3]:= MaximalBy[Reverse[list], Abs, 4]

Out[3]= {5, -5, 4, -4}
```

### Applications (3)

Find the four longest texts available in ``ExampleData["Text"]`` :

```wl
In[1]:= MaximalBy[ExampleData["Text"], StringLength @* ExampleData, 4]

Out[1]= {{"Text", "DonQuixoteIEnglish"}, {"Text", "DonQuixoteISpanish"}, {"Text", "OriginOfSpecies"}, {"Text", "PrideAndPrejudice"}}
```

---

Find the five constellations with maximal number of bright stars:

```wl
In[1]:= MaximalBy[ConstellationData[], Length @* EntityProperty["Constellation", "BrightStars"], 5]

Out[1]= {Entity["Constellation", "Eridanus"], Entity["Constellation", "Orion"], Entity["Constellation", "Cancer"], Entity["Constellation", "Sagittarius"], Entity["Constellation", "Auriga"]}
```

---

Take a dataset of the solar system planets:

```wl
In[1]:= dataset = Dataset[ExampleData[{"Dataset", "Planets"}], MaxItems -> 4]

Out[1]=
Dataset[Association["Mercury" -> Association["Mass" -> Quantity[3.30104`6.*^23, "Kilograms"], 
    "Radius" -> Quantity[2439.7`5., "Kilometers"], "Moons" -> Association[]], 
  "Venus" -> Association["Mass" -> Quantity[4.867320000000000000000001`6.* ... "]], 
      "Psamathe" -> Association["Mass" -> Missing["NotAvailable"], 
        "Radius" -> Quantity[20.`2., "Kilometers"]], 
      "Neso" -> Association["Mass" -> Missing["NotAvailable"], 
        "Radius" -> Quantity[30.`2., "Kilometers"]]]]]]
```

Find the two planets with the maximal mass:

```wl
In[2]:= MaximalBy[dataset, #Mass&, 2]//Keys

Out[2]= Dataset[{"Jupiter", "Saturn"}]
```

### Properties & Relations (3)

``MaximalBy[{e1, e2, …}, f, n]`` compares values ``f[ei]`` using canonical ``Order`` :

```wl
In[1]:= data = {{1, x}, {0, x}, {-Infinity, x}};

In[2]:= MaximalBy[data, First, 2]

Out[2]= {{-∞, x}, {1, x}}

In[3]:= ReverseSort[First /@ data, Order]

Out[3]= {-∞, 1, 0}
```

``TakeLargestBy[{e1, e2, …}, f, n]`` compares values ``f[ei]`` using ``NumericalOrder`` :

```wl
In[4]:= TakeLargestBy[data, First, 2]

Out[4]= {{1, x}, {0, x}}

In[5]:= ReverseSort[First /@ data, NumericalOrder]

Out[5]= {1, 0, -∞}
```

---

For a specific ordering function ``p``, ``MaximalBy[data, f, n, p]`` is equivalent to ``TakeLargestBy[data, f, n, p]`` :

```wl
In[1]:= planets = PlanetData[]

Out[1]= {Entity["Planet", "Mercury"], Entity["Planet", "Venus"], Entity["Planet", "Earth"], Entity["Planet", "Mars"], Entity["Planet", "Jupiter"], Entity["Planet", "Saturn"], Entity["Planet", "Uranus"], Entity["Planet", "Neptune"]}

In[2]:= MaximalBy[planets, EntityProperty["Planet", "Name"], 4, AlphabeticOrder]

Out[2]= {Entity["Planet", "Venus"], Entity["Planet", "Uranus"], Entity["Planet", "Saturn"], Entity["Planet", "Neptune"]}

In[3]:= TakeLargestBy[planets, EntityProperty["Planet", "Name"], 4, AlphabeticOrder]

Out[3]= {Entity["Planet", "Venus"], Entity["Planet", "Uranus"], Entity["Planet", "Saturn"], Entity["Planet", "Neptune"]}
```

---

For association, the function ``f`` is applied to values:

```wl
In[1]:= assoc = <|"a" -> {1, 1}, "b" -> {2, 1}, "c" -> {2, 3}, "d" -> {4, 2}, "e" -> {1, 3}|>;

In[2]:= Values[MaximalBy[assoc, First]] === MaximalBy[Values[assoc], First]

Out[2]= True
```

### Possible Issues (1)

By default, the maximal element is determined using canonical ``Order``, not numerical ordering:

```wl
In[1]:= MaximalBy[{1, 2, 3, Pi, 4}, Identity]

Out[1]= {π}

In[2]:= MaximalBy[{BesselJ[0, 1], BesselJ[1, 1]}, Identity]

Out[2]= {BesselJ[1, 1]}
```

Compare numerical values of the elements of the list:

```wl
In[3]:= MaximalBy[{1, 2, 3, Pi, 4}, N]

Out[3]= {4}

In[4]:= MaximalBy[{BesselJ[0, 1], BesselJ[1, 1]}, N]

Out[4]= {BesselJ[0, 1]}
```

## See Also

* [`MinimalBy`](https://reference.wolfram.com/language/ref/MinimalBy.en.md)
* [`Max`](https://reference.wolfram.com/language/ref/Max.en.md)
* [`TakeLargest`](https://reference.wolfram.com/language/ref/TakeLargest.en.md)
* [`TakeLargestBy`](https://reference.wolfram.com/language/ref/TakeLargestBy.en.md)
* [`FindMaximum`](https://reference.wolfram.com/language/ref/FindMaximum.en.md)
* [`Maximize`](https://reference.wolfram.com/language/ref/Maximize.en.md)
* [`RankedMax`](https://reference.wolfram.com/language/ref/RankedMax.en.md)
* [`ReverseSortBy`](https://reference.wolfram.com/language/ref/ReverseSortBy.en.md)
* [`Ordering`](https://reference.wolfram.com/language/ref/Ordering.en.md)

## Related Guides

* [Math & Counting Operations on Lists](https://reference.wolfram.com/language/guide/MathematicalAndCountingOperationsOnLists.en.md)
* [Functional Programming](https://reference.wolfram.com/language/guide/FunctionalProgramming.en.md)
* [Elements of Lists](https://reference.wolfram.com/language/guide/ElementsOfLists.en.md)
* [Function Composition & Operator Forms](https://reference.wolfram.com/language/guide/FunctionCompositionAndOperatorForms.en.md)
* [Tabular Objects](https://reference.wolfram.com/language/guide/TabularObjects.en.md)

## History

* [Introduced in 2014 (10.0)](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn100.en.md) \| [Updated in 2015 (10.3)](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn103.en.md) ▪ [2025 (14.2)](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn142.en.md)