flatten function in DataWeave 2.0 (mulesoft)

The flatten to move the elements from the subarrays to the parent array, eliminate the subarrays, and covert all key-value pairs into a list of objects within the parent array. With the help of flatten function multiple arrays are bounded together as single array.

Syntax:
flatten<T, Q>(@StreamCapable items: Array<Array<T> | Q>): Array<T | Q>

Turns a set of subarrays (such as [ [1,2,3], [4,5,[6]], [], [null] ]) into a single, flattened array (such as [ 1, 2, 3, 4, 5, [6], null ]).

Parameters

NameDescription
itemsThe input array of arrays made up of any supported types.
Input
[ [1,2,3], [4,5,[6]], [], [null] ]
DW Script
%dw 2.0
output application/json
---
flatten(payload)
Output
[
  1,
  2,
  3,
  4,
  5,
  [
    6
  ],
  null
]

Note that it flattens only the first level of subarrays and omits empty subarrays.

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 ]
Follow Me

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

Instagram

Facebook

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago