views:

255

answers:

2

Assume we have

$a = @(1, @(2, @(3)))

I whould like to flatten $a to get @(1, 2, 3)

I have found a solution

@($a | % {$_}).count

But may be there is a more elegant way?

+3  A: 

Piping is the correct way to flatten nested structures, so I'm not sure what would be more "elegant". Yes, the syntax is a bit line-noisy looking, but frankly quite serviceable.

Godeke
+1  A: 

Same code, just wrapped in function:

function Flatten($a)
{
    ,@($a | % {$_})
}

Testing:

function AssertLength($expectedLength, $arr)
{
    if($ExpectedLength -eq $arr.length) 
    {
        Write-Host "OK"
    }
    else 
    {
        Write-Host "FAILURE"
    }
}

# Tests
AssertLength 0 (Flatten @())
AssertLength 1 (Flatten 1)
AssertLength 1 (Flatten @(1))
AssertLength 2 (Flatten @(1, 2))
AssertLength 2 (Flatten @(1, @(2)))
AssertLength 3 (Flatten @(1, @(2, @(3))))
alex2k8