DataWeave has several function to find the highest or lowest value in an array. The items in the array need to be of the same type and implement the Comparable
interface. To find the highest value we can use the max
function. The function returns the maximum value based on the type of the item in the array. If we want to find the highest value based on other criteria we can use the maxBy
function. This function takes a lambda as last argument where we can return a Comparable
value that is used to determine the highest value. To find the lowest value in an array we have similar functions: min
and minBy
.
In the following example we use several ways to find the highest and lowest value in arrays with items of different types:
Source
%dw 2.0 // Array with numbers var numbers = [10, 2, 3, 1, 20] // Array with string values var languages = ["DataWeave", "Java", "Groovy", "Clojure"] // Array with objects representing a user var users = [ { name: "mrhaki", age: 47 }, { name: "alice", age: 32 }, { name: "bob", age: 61 } ] output application/json --- { // Find maximum for numbers maxNumbers: max(numbers), // Find minimum for numbers minNumbers: min(numbers), // Find max for srings looks at first character maxLanguages: max(languages), // Find min for strings looks at first character minLanguages: min(languages), // Find language with max length maxByLength1: maxBy(languages, (lang) -> sizeOf(lang)), // Find max with infix notation maxByLength2: languages maxBy (lang) -> sizeOf(lang), // Find max with infix notation and $ to reference lambda argument maxByLength3: languages maxBy sizeOf($), // Find language with minimal length minByLength: languages minBy ((lang) -> sizeOf(lang)), // Find oldest user with maxBy on objects oldestUser: users maxBy ((user) -> user.age), // Find youngest user with minBy on objects youngestUser: users minBy (user) -> user.age }
Output
{ "maxNumbers": 20, "minNumbers": 1, "maxLanguages": "Java", "minLanguages": "Clojure", "maxByLength1": "DataWeave", "maxByLength2": "DataWeave", "maxByLength3": "DataWeave", "minByLength": "Java", "oldestUser": { "name": "bob", "age": 61 }, "youngestUser": { "name": "alice", "age": 32 } }
Written with DataWeave 2.4.