Flatten array in PowerShell

后端 未结 3 955
天涯浪人
天涯浪人 2021-02-07 01:29

Assume we have:

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

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

I have found one solution

3条回答
  •  你的背包
    2021-02-07 02:28

    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))))
    

提交回复
热议问题