0

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Recursive it is then. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.