Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$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:
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 3 4 5 |
IDS: 0,1,2 IDS: 3,4,5 IDS: 6,7,8 IDS: 9 |
What am I missing?
Answer:
You can use ,$x
instead of just $x
.
The about_Operators
section in the documentation has this:
1 2 3 4 5 |
, 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. |