Search code examples
arrayspowershelldata-partitioning

Slice a PowerShell array into groups of smaller arrays


I would like to convert a single array into a group of smaller arrays, based on a variable. So, 0,1,2,3,4,5,6,7,8,9 would become 0,1,2,3,4,5,6,7,8,9 when the size is 3.

My current approach:

$ids=@(0,1,2,3,4,5,6,7,8,9)
$size=3

0..[math]::Round($ids.count/$size) | % { 

    # slice first elements
    $x = $ids[0..($size-1)]

    # redefine array w/ remaining values
    $ids = $ids[$size..$ids.Length]

    # return elements (as an array, which isn't happening)
    $x

} | % { "IDS: $($_ -Join ",")" }

Produces:

IDS: 0
IDS: 1
IDS: 2
IDS: 3
IDS: 4
IDS: 5
IDS: 6
IDS: 7
IDS: 8
IDS: 9

I would like it to be:

IDS: 0,1,2
IDS: 3,4,5
IDS: 6,7,8
IDS: 9

What am I missing?


Solution

  • You can use ,$x instead of just $x.

    The about_Operators section in the documentation has this:

    , Comma operator                                                  
       As a binary operator, the comma creates an array. As a unary
       operator, the comma creates an array with one member. Place the
       comma before the member.