---
schema_version: "1"
id: 9708517f9dc53eb2de0e4f9567f95d7707deba170882be2f9f855d8079503678
title: Map and Flatten an Array
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/dataweave/2.4/dataweave-cookbook-map-and-flatten.md
canonical_url: https://docs.mulesoft.com/dataweave/2.4/dataweave-cookbook-map-and-flatten
source_site: docs.mulesoft.com
content_type: documentation
content_hash: ffeaccfc668d9ce65169c0439cca882becf31d1aced7a31aad2a2a3126155552
description: MuleSoft Documentation Site
release: "2.4"
latest: false
---
---
product: DataWeave
version: 2.4
keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping
---

# Map and Flatten an Array

> For the full documentation index, see: https://docs.mulesoft.com/llms.txt

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:

```dataweave
%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:

    ```json
    [[], [{ "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:

    ```json
    [
      {
        "name": 3
      },
      {
        "name": 5
      },
      {
        "name": 3
      }
    ]
    ```

## See Also

- [flatMap](https://docs.mulesoft.com/dataweave/2.4/dw-core-functions-flatmap)
