max_by

Get element from array with a maximum value of specified comparison function

Definition

object max_by(array[object] elements, expression->number|expression->string expr)

Returns the maximum element in an array of objects using the expression expr as the comparison key. In case of ties, the first object achieving the maximum evaluation is returned.

Parameters

array[object] elements

An array to find the maximum of by some metric.

expression->number | expression->string expr

The expression needs to return a string or a number since these are the only types that are comparable to each other. Select a property of the object, or define a function that evaluates the objects in some other way in order to compare them.

Returns

object

A maximum object from elements based on expr.

Examples

{
  "people":
    [
      {"name": "Julia", "age": 30},
      {"name": "Alexander", "age": 57},
      {"name": "Pete", "age": 71},
      {"name": "Selma", "age": 42}
    ]
}
{
  alphabeticallyLastName: max_by(people, @.name),
  oldestPerson: max_by(people, @.age),
  longestName: max_by(people, length(@.name)).name,
  arrayWithLargestAverage: max_by(`[[1, 2, 3], [1, 4, 5]]`, &avg(@)),     
  outlierFurthestFromAverage: max_by($.arrayWithLargestAverage,
                                     &abs(subtract(@, avg($.arrayWithLargestAverage))))
}
{
  "alphabeticallyLastName": {"name": "Selma", "age": 42},
  "oldestPerson": {"name": "Pete", "age": 71},
  "longestName": "Alexander",
  "arrayWithLargestAverage": [1, 4, 5],
  "outlierFurthestFromAverage": 1
}