The filter Function (and Function Type Signatures) In DataWeave Mule 4

Filter

This function can be applied to an array. It iterates the array and matches the values with the expression. The output of the filter function is an array with the matching values.

The expression must return true or false. If the expression returns true for a value or index in the array, the value gets captured in the output array. If it returns false for a value or index in the array, that item gets filtered out of the output. If there are no matches, the output array will be empty.

The lambda takes in two arguments, a single item of type Any, and a index of type Number. It returns a Boolean. We can use a syntax that is very close to DataWeave to define this:

filter<T>(@StreamCapable items: Array<T>, criteria: (item: T, index: Number) -> Boolean): Array<T>

filter(Array<Any&gt;, ((Any, Number) -&gt; Boolean)) : Array<Any&gt;

Examples:

Input Payload:
{
  "Id": "1184001100000000517",
  "marketCode": "US",
  "languageCode": "en-US",
  "profile": {
  "base": {
     "username": "TheMule",
     "activeInd": "R",
     "phone": [
       {
          "activeInd": "Y",
          "type": "mobile",
          "primaryInd": "Y",
          "number": "230678123"
       },
       {
         "activeInd": "N",
         "type": "mobile",
         "primaryInd": "N",
         "number": ""
       },
       {
          "activeInd": "Y",
          "type": "mobile",
          "primaryInd": "Y",
          "number": "154896523"
       }

      ]
    }
  }
 }
Dataweave Script:
%dw 2.0
output application/json
---
{
    id: payload.Id,
    markCode: payload.marketCode,
    languageCode: payload.languageCode,
    username: payload.profile.base.username,
    phoneNumber: (payload.profile.base.phone filter ($.activeInd == "Y" and $.primaryInd== "Y")).number default []
}
Output Payload:
{
  "id": "1184001100000000517",
  "markCode": "US",
  "languageCode": "en-US",
  "username": "TheMule",
  "phoneNumber": [
    "230678123"
    "154896523"
  ]
}

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago