Powershell join array values

1.9k views Asked by At

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

2

There are 2 answers

0
mklement0 On BEST ANSWER
$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.

0
harper On

You can create a matrix with this approach

# your input
$a = @('Blue','red','green') 
$b = @('car', 'bike')
# create an empty result array
$result = @()
# iterate the input arrays and add the items to the result
$b | ForEach-Object { $x=$_; $a | ForEach-Object { $result +=  "$_ $x" } }

The += operator is not very efficient. It will create a new instance of the result for each iteration. This might work for small input arrays.