Search code examples
arrayspowershellcross-product

Powershell join array values


I'm looking to cross combine values of arrays to create new array. example,

$a = @('Blue','red','green') 
$b = @('car', 'bike') 

to something like

('blue car','red car','green car') and ('blue bike','red bike','green bike')

PS: this is not simple concatenate function I'm looking.

Thanks, Nilay


Solution

  • $a = @('Blue', 'red', 'green') 
    $b = @('car', 'bike') 
    
    $outArrays = @(), @() # Initialize a 2-element array.
    $i = 0
    foreach ($elB in $b) {
      $outArrays[$i++] = foreach ($elA in $a) { "$elA $elB" }
    }
    
    • $outArrays[0] now contains 'blue car', 'red car', 'green car'
    • $outArrays[1] now contains 'blue bike', 'red bike', 'green bike'

    The above takes advantage of PowerShell's ability to use loop statements such as foreach as expressions, with PowerShell implicitly collecting all outputs from the loop in an array ([object[]]; assuming two or more outputs).


    General information about array concatentation:

    To create a flat array, by concatenation, simply use +:

    # Creates a flat array with 5 elements:
    #   @('Blue', 'red', 'green', 'car', 'bike')
    $a + $b
    

    To create a two-element nested array, use the unary form of ,, the array constructor operator:

    # -> Nested 2-element array:
    # * Element 0 contains @('Blue', 'red', 'green')
    # * Element 1 contains: @('car', 'bike')
    , $a + , $b
    

    As an aside: note that you don't strictly need @(...), the array-subexpression operator to create array literals; e.g.,
    $a = 'Blue', 'red', 'green' will do.