Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "zip" two arrays in PowerShell?

I want to zip two arrays, like how Ruby does it, but in PowerShell. Here's a hypothetical operator (I know we're probably talking about some kind of goofy pipeline, but I just wanted to show an example output).

PS> @(1, 2, 3) -zip @('A', 'B', 'C')
@(@(1, 'A'), @(2, 'B'), @(3, 'C'))
like image 801
Anthony Mastrean Avatar asked Mar 30 '17 15:03

Anthony Mastrean


People also ask

How do you zip two arrays in Python?

If we have two 1D arrays and want to zip them together inside a 2D array, we can use the list(zip()) function in Python. This approach involves zipping the arrays together inside a list. The list(zip(a,b)) function takes the arrays a and b as an argument and returns a list.

How do I create an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

How do you access array elements in PowerShell?

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar. length-1.


1 Answers

There's nothing built-in and it's probably not recommended to "roll your own" function. So, we'll take the LINQ Zip method and wrap it up.

[System.Linq.Enumerable]::Zip((1, 2, 3), ('A', 'B', 'C'), [Func[Object, Object, Object[]]]{ ,$args })

That works, but it's not pleasant to work with over time. We can wrap the function (and include that in our profile?).

function Select-Zip {
    [CmdletBinding()]
    Param(
        $First,
        $Second,
        $ResultSelector = { ,$args }
    )

    [System.Linq.Enumerable]::Zip($First, $Second, [Func[Object, Object, Object[]]]$ResultSelector)
}

And you can call it simply:

PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C'
1
A
2
B
3
C

With a non-default result selector:

PS> Select-Zip -First 1, 2, 3 -Second 'A', 'B', 'C' -ResultSelector { param($a, $b) "$a::$b" }
1::A
2::B
3::C

I leave the pipeline version as an exercise to the astute reader :)

PS> 1, 2, 3 | Select-Zip -Second 'A', 'B', 'C'
like image 111
Anthony Mastrean Avatar answered Oct 26 '22 20:10

Anthony Mastrean