Translate

Wednesday 28 February 2024

Find the smallest and greatest number in an array in MuleSoft 78

Find the smallest and greatest number in an array in MuleSoft


Here's how to find the smallest and greatest number in an array in MuleSoft 4 using DataWeave:

1. Finding the Smallest Number:


XML


%dw 2.0
output application/json

var numbers = [10, 20, 5, 30, 15];

// Find the smallest number using min function
var smallestNumber = min(numbers);

write(smallestNumber);

Explanation:

  1. DataWeave Version: This example specifies DataWeave version 2.0.

  2. Output Format: Defines the output format as JSON.

  3. Array: Defines an array named numbers containing the values.

  4. Smallest Number:

  • The min function takes an array of elements as input.

  • It returns the element with the least value among all elements in the array.

  1. Output: The write function displays the smallest number.

2. Finding the Greatest Number:


XML


%dw 2.0
output application/json

var numbers = [10, 20, 5, 30, 15];

// Find the greatest number using max function
var greatestNumber = max(numbers);

write(greatestNumber);

Explanation:

  1. DataWeave Version: Same as before.

  2. Output Format: Same as before.

  3. Array: Same array used.

  4. Greatest Number:

  • The max function takes an array of elements as input.

  • It returns the element with the greatest value among all elements in the array.

  1. Output: The write function displays the greatest number.

Combining Both:

You can combine these approaches into a single DataWeave script:


XML


%dw 2.0
output application/json

var numbers = [10, 20, 5, 30, 15];

// Find smallest and greatest numbers
var smallestNumber = min(numbers);
var greatestNumber = max(numbers);

write({
  "smallestNumber": smallestNumber,
  "greatestNumber": greatestNumber
});

This will output a JSON object with both the smallest and greatest numbers.

Additional Notes:

  • These functions work with numbers and strings that can be compared lexicographically (e.g., alphabetical order for strings).

  • For custom objects, you might need to define your own comparison logic within DataWeave.

These examples demonstrate how to find the smallest and greatest number in an array using DataWeave in MuleSoft 4. Remember to adapt the code and data according to your specific requirements.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.