Question:
I have an object which contains 7 items.
1 2 3 4 5 6 |
$obj.gettype().name Object[] $obj.length 7 |
I want to loop through in batches of 3. I do NOT want to use the modulus function, I actually want to be able to create a new object with just the 3 items from that batch. Pseudo code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$j=0 $k=1 for($i=0;$i<$obj.length;$i+=3){ $j=$i+2 $myTmpObj = $obj[$i-$j] # create tmpObj which contains items 1-3, then items 4-6, then 7 etc echo "Batch $k foreach($item in $myTmpObj){ echo $item } $k++ } Batch 1 item 1 item 2 item 3 Batch 2 item 4 item 5 item 6 Batch 3 Item 7 |
Regards,
ted
Answer:
Your pseudo code is almost real. I have just changed its syntax and used the range operator (..
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# demo input (btw, also uses ..) $obj = 1..7 $k = 1 for($i = 0; $i -lt $obj.Length; $i += 3) { # end index $j = $i + 2 if ($j -ge $obj.Length) { $j = $obj.Length - 1 } # create tmpObj which contains items 1-3, then items 4-6, then 7 etc $myTmpObj = $obj[$i..$j] # show batches "Batch $k" foreach($item in $myTmpObj) { $item } $k++ } |
The output looks exactly as required.