min_by

Find the element in an array with a minimum value of a specified comparison function

Definition

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

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

Parameters

array[object] elements

An array of objects to find the minimum 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 minimum object from elements based on expr.

Examples

{
  "people":
    [
      {"name": "Julia", "age": 30},
      {"name": "Alexander", "age": 57},
      {"name": "Pete", "age": 71},
      {"name": "Selma", "age": 42}
    ]
}
{
  alphabeticallyFirstName: min_by(people, @.name),
  youngestPerson: min_by(people, @.age),
  shortestName: min_by(people, length(@.name)).name,
  arrayWithLowestAverage: min_by(`[[1, 4, 5], [6, 7, 8]]`, &avg(@)),     
  elementClosestToAverage: min_by($.arrayWithLowestAverage, 
                                  &abs(subtract(@, avg($.arrayWithLowestAverage))))
}
{
  "a": {"name": "Alexander", "age": 57},
  "b": {"name": "Julia", "age": 30},
  "c": "Pete",
  "arrayWithLowestAverage": [1, 4, 5],
  "elementClosestToAverage": 4
}