Contact Us 1-800-596-4880

Map and Flatten an Array

The flatMap function calls map on an input and wraps the results in a call to flatten.

The flatMap function is useful for refactoring uses of flatten on the results of a call to map. For example, review the following DataWeave script:

DataWeave Script:
%dw 2.0
output application/json
var myData = [{name:1},{name:2},{name:3}]
fun myExternalFunction(data): Array =
    if(data.name == 1)
        []
    else if(data.name == 2)
        [{name: 3}, {name:5}]
    else
        [data]
---
//flatten(myData map ((item, index) -> myExternalFunction(item)))
myData flatMap ((item, index) -> myExternalFunction(item))

The header of the script creates a variable myData to define an array of objects, each with the key name. It also defines a function with a set of if-else statements that act on name-value pairs with the key name.

The body of the DataWeave script contains the following expressions, each of which produces the same result:

  • flatten(myData map ((item, index) → myExternalFunction(item)))

  • myData flatMap ((item, index) → myExternalFunction(item))

Whether you use the flatMap expression or explicitly use flatten to wrap the map expression, the following takes place:

  1. The expression maps the items in the input array according to if-else conditions in the function myExternalFunction(), which is defined in the header.

    The mapping produces the following output:

    [
      [
      ],
      [
        { "name": 3 },
        { "name": 5 }
      ],
      [
        { "name": 3 }
      ]
    ]
  2. The expression flattens the mapped results by consolidating the elements from the subarrays into a single array, removing the parent array and eliminating the empty child array.

    Flattening produces the following output:

    Output JSON:
    [
      {
        "name": 3
      },
      {
        "name": 5
      },
      {
        "name": 3
      }
    ]

See Also