Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flattenDeep: Function to get an array flattened recursively by sublevels #54

Open
VictorManhani opened this issue Feb 15, 2023 · 0 comments

Comments

@VictorManhani
Copy link

We often have the need to flatten an array of arrays. However, there are cases where it is necessary to convert an array of multi-level arrays, but DataWeave does not have an out-of-the-box function for this, nor an easy solution that solves the scenarios where the sub-levels are composed with Array and Range. And besides, I miss setting the flattening level in the sublevels.

So we thought and created a function to facilitate our planning with these features and improvements. The name of this function is flattenDeep containing two input parameters, the 1st parameter being the array of elements and the 2nd parameter the flattening level. Here is the example of the function:

%dw 2.0
output application/json

fun flattenDeep(arr: Array, level: Number) = arr flatMap (if ((typeOf($) matches /Range|Array/) and level > 0) flattenDeep($, level - 1) else [$])

var arrLevels = [0,9,3.1,[1,'¬',[3,'4', ['a','b', (1 to 3), ['açaí', 'banana', 'chocolate', [134]], null], true, false], {}], {"name": "Ronaldo", "codename": "Victor"}]
---
flattenDeep(arrLevels, 4)
// arrLevels flattenDeep 4

Expected Output:

[
	0,
	9,
	3.1,
	1,
	"¬",
	3,
	"4",
	"a",
	"b",
	1,
	2,
	3,
	"açaí",
	"banana",
	"chocolate",
	[134],
	null,
	true,
	false,
	{},
	{
		"name": "Ronaldo",
		"codename": "Victor"
	}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant