Contact Free trial Login

flatten

flatten(Array<Array<T> | Q>): Array<T | Q>

Turns a nested array (such as [ [1], [2] ]) into a simple array (such as [1, 2]).

Parameters

Name Description

items

The input array of arrays made up of any supported types.

Example

This example defines three arrays of numbers, creates another array containing those three arrays, and then uses the flatten function to convert the array of arrays into a single array with all values.

Source

%dw 2.0
output application/json
var array1 = [1,2,3]
var array2 = [4,5,6]
var array3 = [7,8,9]
var arrayOfArrays = [array1, array2, array3]
---
flatten(arrayOfArrays)

Output

[ 1,2,3,4,5,6,7,8,9  ]

Example

This example returns a single array from a nested array of objects.

Source

%dw 2.0
var myData =
{ user : [
   {
     group : "dev",
     myarray : [
       { name : "Shoki", id : 5678 },
       { name : "Mariano", id : 9123 }
     ]
   }
 ]
}
output application/json
---
flatten(myData.user.myarray)

Output

[
  {
    "name": "Shoki",
    "id": 5678
  },
  {
    "name": "Mariano",
    "id": 9123
  }
]

Note that if you use myData.user.myarray to select the array of objects in myarray, instead of using flatten(myData.user.myarray), the output is a nested array of objects:

[
  [
    {
      "name": "Shoki",
      "id": 5678
    },
    {
      "name": "Mariano",
      "id": 9123
    }
  ]
]

flatten(Null): Null

Helper function that allows flatten to work with null values.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub