Translate

New Live Courses

🚀 *Gen AI Engineer Telugu (Production Focused)*
🗓️ *Date:* 30th Sept 2026, 07:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
🗓️ *Date:* 30th Sept 2026, 08:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/7r
👥 *Join WA Community:*
https://www.vlrt.in/7w
💡*Course Content:*
https://www.vlrt.in/7c
▶️ *Demo Videos:*
https://www.vlrt.in/7v

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 30th Sept 2026, 09:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

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.