I have an object which contains 7 items.
$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:
$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
Your pseudo code is almost real. I have just changed its syntax and used the range operator (..
):
# 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.
See if this one may work as required (I assume your item n is an element of $obj
)
$obj | % {$i=0;$j=0;$batches=@{}} if($i!=3 and $batches["Batch $j"]) { $batches["Batch $j"]+=$_; $i+=1 } else {$i=1;$j+=1;$batches["Batch $j"]=@($_)} } {$batches}
Should return an HashTable ($batches
) with keys such as "Batch 1"
, "Batch 2"
, ... each key related to an array of three items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With