Translate

Tuesday 27 February 2024

Filter out even & odd numbers from an array in MuleSoft 74

  Filter out even & odd numbers from an array in MuleSoft 


Filtering Even and Odd Numbers in MuleSoft 4

Here's how you can filter even and odd numbers from an array in MuleSoft 4 using DataWeave:

Filtering Even Numbers:


XML


%dw 2.0
output application/json

var numbers = [1, 2, 3, 4, 5, 6];

// Filter even numbers using modulo operator (%)
var evenNumbers = numbers filter ((item) => mod(item, 2) == 0);

write(evenNumbers);

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. Filtering:

  • The filter expression iterates through each item in the numbers array.

  • The inner expression mod(item, 2) == 0 checks if the remainder of dividing the item by 2 is 0 (even).

  • Only elements where the condition is true are added to the evenNumbers array.

  1. Output: The write function displays the filtered array evenNumbers.

Filtering Odd Numbers:

To filter odd numbers, simply modify the filter condition:


XML


%dw 2.0
output application/json

var numbers = [1, 2, 3, 4, 5, 6];

// Filter odd numbers using modulo operator and negation
var oddNumbers = numbers filter ((item) => mod(item, 2) != 0);

write(oddNumbers);

This code uses the negation operator (!=) to include items where the remainder is not 0 (odd).

Additional Notes:

  • You can adapt this approach to filter based on other criteria by modifying the condition within the filter expression.

  • DataWeave offers other functionalities like comprehensions for more concise filtering if needed.

This example demonstrates how to filter even and odd numbers using DataWeave within MuleSoft 4. Remember to adapt the code and logic based on your specific data and desired filtering goals.


No comments:

Post a Comment

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