Contact Us 1-800-596-4880

minBy

minBy<T>(@StreamCapable array: Array<T>, criteria: (item: T) -> Comparable): T | Null

Iterates over an array to return the lowest value of comparable elements from it.

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

Parameters

Name Description

item

Element in the input array (of type Number, Boolean, DateTime, LocalDateTime, Date, LocalTime, Time, or TimeZone). Can be referenced with $.

Example

This example returns the lowest 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 } ] minBy $.a

Source

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

Output

{ "a" : 1 }

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
---
{
  myMinBy: {
    byDateTime: [ myDateTime1, myDateTime2 ] minBy ((item) -> item),
    byDate: [ myDateTime1 as Date, myDateTime2 as Date ] minBy ((item) -> item),
    byTime: [ myDateTime1 as Time, myDateTime2 as Time ] minBy ((item) -> item),
    aBoolean: [ true, false, (0 > 1), (1 > 0) ] minBy $,
    emptyArray: [] minBy ((item) -> item)
  }
}

Output

{
  "myMinBy": {
    "byDateTime": "2017-10-01T22:57:59-03:00",
    "byDate": "2017-10-01",
    "byTime": "22:57:59-03:00",
    "aBoolean": false,
    "emptyArray": null
  }
}