Contact Free trial Login

maxBy

maxBy(Array<T>, (item: T) -> Comparable): T | Null

Iterates over an array and returns the highest value of comparable elements from it.

The items need to be of the same type. maxBy returns an error if they are not, and it returns null when the array is empty.

Parameters

Name Description

array

The input array.

criteria

Expression for selecting an item from the array, where the item is a Number, Boolean, DateTime, LocalDateTime, Date, LocalTime, Time, or TimeZone data type. Can be referenced with $.

Example

This example returns the greatest numeric value within objects (key-value pairs) in an array. Notice that it uses item.a to select the value of the object. You can also write the same expression like this, using an anonymous parameter: [ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy $.a

Source

%dw 2.0
output  application/json
---
[ { "a" : 1 }, { "a" : 3 }, { "a" : 2 } ] maxBy ((item) -> item.a)

Output

{ "a" : 3 }

Example

This example gets the latest DateTime, Date, and Time from inputs defined in the variables myDateTime1 and myDateTime2. It also shows that the function returns null on an empty array.

Source

%dw 2.0
var myDateTime1 = "2017-10-01T22:57:59-03:00"
var myDateTime2 = "2018-10-01T23:57:59-03:00"
output application/json
---
{
  myMaxBy: {
    byDateTime: [ myDateTime1, myDateTime2 ] maxBy ((item) -> item),
    byDate: [ myDateTime1 as Date, myDateTime2 as Date ] maxBy ((item) -> item),
    byTime: [ myDateTime1 as Time, myDateTime2 as Time ] maxBy ((item) -> item),
    emptyArray: [] maxBy ((item) -> item)
  }
}

Output

{
  "myMaxBy": {
    "byDateTime": "2018-10-01T23:57:59-03:00",
    "byDate": "2018-10-01",
    "byTime": "23:57:59-03:00",
    "emptyArray": null
  }
}

We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.