max_by

Modified on Thu, 9 Jul at 10:49 AM

max_by

TABLE OF CONTENTS

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

Sample data
{
  "people":
    [
      {"name": "Julia", "age": 30},
      {"name": "Alexander", "age": 57},
      {"name": "Pete", "age": 71},
      {"name": "Selma", "age": 42}
    ]
}
Transformation
{
  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))))
}
Result
{
  "alphabeticallyLastName": {"name": "Selma", "age": 42},
  "oldestPerson": {"name": "Pete", "age": 71},
  "longestName": "Alexander",
  "arrayWithLargestAverage": [1, 4, 5],
  "outlierFurthestFromAverage": 1
}

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