0

What I have?

$array1 = "string01", "string02", "string03"

$array2 = "another01", "antoher02", "anoter03"

What I wish?

output-file:

  • Example01:

string01,another01

string02,another02

string03,another03

How can I cocatenate two arrays in one and do that line by line? It's because I need to combine value 01 from $array01 with value01 from $array02, separating them with comma.

I have tried to use foreach, but this one combine every value from $array01 with every value from $array02, for example:

  • Example02:

string01,another01

string01,another02

string01,another03

string02,another01

string02,another02

string02,another03

string03,another01

string03,another02

string03,another03

But I need the output likes the Example01.

I am using powershell! Thanks

I have tried to use foreach, but this one combine every value from $array01 with every value from $array02, but no success doing that!

mklement0
  • 382,024
  • 64
  • 607
  • 775

3 Answers3

1

You would use a For loop to do this simply. Something like:

For($i=0; $i -lt $array1.count; $i++){
    $array1[$i],$array2[$i] -join ','
}
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
1

Enumerable.Zip does exactly what you're looking for:

$array1 = 'string01', 'string02', 'string03'
$array2 = 'another01', 'antoher02', 'anoter03'

[System.Linq.Enumerable]::Zip(
    [string[]] $array1,
    [string[]] $array2,
    [Func[string, string, string]] {param($x, $y) "$x,$y" })

# Outputs:
# string01,another01
# string02,antoher02
# string03,anoter03
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
0

I did this with a ForEach loop. There are probably a million ways to skin this cat.

ForEach($x in $array1){
    $index = $array1.IndexOf($x)
    $combined += @($array1[$index] + "," + $array2[$index])
}

In the above block the current item in the loop is going to be $x, we get the index of $x from $array1 because that's the array we are looping. We just use that index on the other array, and we glue it all together by concatenating with "+" symbols.

Output of $combined:

string01,another01
string02,antoher02
string03,anoter03
shadow2020
  • 1,315
  • 1
  • 8
  • 30