Reputation: 584
Let's say I have an array:
$stringArray = @('a', 'b', 'c')
To get a joined string out of it I do something like this:
$stringArray -join ','
It will result in
a,b,c
What do I need to do (in a clean and efficient way), if I have
$stringArray = @(@('a1','a2','a3'), 'b', 'c')
and I want to get
a1,a2,a3,b,c
???
UPDATE: My current script is this:
($stringArray | %{$_ -join ','}) -join ','
but the dimension of this jagged array is hardcoded (i.e. it only works with arrays of arrays, not with arrays of arrays of arrays). Anything more elegant and flexible?
Upvotes: 0
Views: 532
Reputation: 61028
What you need is a recursive helper function to flatten the array.
Something like this:
function Flatten-Array([array]$a) {
$a | ForEach-Object {
if ($_ -is [array]) { Array-Flatten $_ } else {$_ }
}
}
Usage:
$stringArray = @(@('a1','a2','a3'), 'b', 'c')
$flatArray = Flatten-Array $stringArray
$flatArray -join ',' # --> a1,a2,a3,b,c
Or with deeper nested arrays:
$stringArray = @('X','Y','Z',@(@('a1','a2','a3',@(3,4,5)), 'b', 'c'))
$flatArray = Flatten-Array $stringArray
$flatArray -join ',' # --> X,Y,Z,a1,a2,a3,3,4,5,b,c
Upvotes: 3