min_by

Modified on Thu, 9 Jul at 10:49 AM

min_by

TABLE OF CONTENTS

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

Sample data
{
  "people":
    [
      {"name": "Julia", "age": 30},
      {"name": "Alexander", "age": 57},
      {"name": "Pete", "age": 71},
      {"name": "Selma", "age": 42}
    ]
}
Transformation
{
  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))))
}
Result
{
  "a": {"name": "Alexander", "age": 57},
  "b": {"name": "Julia", "age": 30},
  "c": "Pete",
  "arrayWithLowestAverage": [1, 4, 5],
  "elementClosestToAverage": 4
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article