Contact Us 1-800-596-4880

maxBy

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

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 throws 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
  }
}