Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested arrays in Powershell

Tags:

powershell

Given this input:

$values = @(1, @(2, 3), $null, @(@(4), 5), 6)

What is necessary to create a clean iteration/pipeline over

1,2,3,4,5,6

?

Conditions:

  • It should not include $null in the output.
  • It should result in an empty array even if the input is $null or all of the input's values are $null.

Bonus:

  • It should show [1,2,3,4,5,6] as the result of ConvertTo-Json -Compress
  • It should preferably be clean and memorable, i.e. non-byzantine pipe manipulation preferred, no dependency on custom functions, if that is at all possible.

I've seen Flatten array in PowerShell, the solutions there do not seem to fulfill the conditions.

like image 534
Tomalak Avatar asked Nov 05 '15 11:11

Tomalak


Video Answer


1 Answers

@(1, @(2, 3), $null, @(@(4), 5), 6) | %{$_} | ?{$_ -ne $null}

The output:

1
2
3
4
5
6

The ForEach-Object cmdlet (%) flattens arrays by default.

like image 145
denisvlah Avatar answered Sep 26 '22 00:09

denisvlah