locked
Array to access each element of other arrays RRS feed

  • Question

  • Hi,

    I have 2 arrays, and I would like to join each elements of these arrays in an ascending order separated by commas.

    Example:

    $A = 1,2,3,4,5,6
    $B = 7,8,9,10,11,12

    And I would like to have them stored in a third array whose elements would be combination of each elements of these 2 arrays separated by comma and in ascending order like:

    $C[0] =1,7

    $C[1] =2,8

    $C[2] =3,9

    $C[3] =4,10

    $C[4] =5,11

    $C[5] =6,12

    Tried the code below but got an error "Index was outside the bounds of the array. At line:12 char:1"

    My CODE:

    $A = @()
    $B = @()
    $C =@()

    $A = 1,2,3,4,5,6
    $B = 7,8,9,10,11,12

    [int]$Z = $A.length-1

    $i=0
    DO{
    $C[$i] = $A[$i], $B[$i] -join","
    $i++
    Write-Host "Value of  i is $i"
    } Until($i = $Z)

    Write-Host "Value of Z is $Z"
    Write-Host "C is $C[$i]"

    Kindly Advice.



    • Edited by HaniMK Wednesday, July 4, 2018 4:36 PM
    Wednesday, July 4, 2018 4:32 PM

Answers

  • $a = 1..6
    $b = 7..12
    $c = ,$null * $a.count
    for ($i=0; $i -lt $a.count; $i++) {
        $c[$i] = $a[$i], $b[$i] -join ','
    }
    $c



    • Edited by Leif-Arne Helland Wednesday, July 4, 2018 5:48 PM
    • Marked as answer by HaniMK Thursday, July 5, 2018 4:24 PM
    Wednesday, July 4, 2018 5:39 PM

All replies

  • $a = 1..6
    $b = 7..12
    $c = ,$null * $a.count
    for ($i=0; $i -lt $a.count; $i++) {
        $c[$i] = $a[$i], $b[$i] -join ','
    }
    $c



    • Edited by Leif-Arne Helland Wednesday, July 4, 2018 5:48 PM
    • Marked as answer by HaniMK Thursday, July 5, 2018 4:24 PM
    Wednesday, July 4, 2018 5:39 PM
  • Here another proposal:
    $i = 0
    $c = @(($a | % {$_,$b[$i++] -join ','}))
    $c
    wizend
    Wednesday, July 4, 2018 6:39 PM
  • A 3rd one:

    [Array]$A=@(1..6)
    [Array]$B=@(7..12)
    [Array]$C=@()
    for($i=0;$i-lt $A.Count;$i++){
        $C+= "$($A[$i]),$($B[$i])"
    }
    
    $C
    

    Wednesday, July 4, 2018 6:55 PM
  • Here another proposal:
    $i = 0
    $c = @(($a | % {$_,$b[$i++] -join ','}))
    $c
    wizend

    Nice one.

    If you want to get rid of $i:

    $a = 1..6
    $b = 7..12
    $c = @(($a | % {$_,$b[$a.IndexOf($_)] -join ','}))
    $c

    Wednesday, July 4, 2018 7:12 PM
  • Assuming that $a is an array of more than one element, the @() is not needed to ensure that $c is an array.

    There is a short version of the loop with $i:

    $a = 1..6
    $b = 7..12
    
    $c = $a | foreach{$i=0}{$_,$b[$i] -join ","; $i++}

    "Foreach" can have 1 to 3 arguments. With 3 arguments, the first is done at start, the next is the loop and the last is done at the end (which is not used here).

     
    • Edited by hpotsirhc Thursday, July 5, 2018 9:17 AM
    Thursday, July 5, 2018 9:16 AM