Created
March 18, 2025 22:23
-
-
Save PanosGreg/9b4cf0cb68e31588f3885a8b28544180 to your computer and use it in GitHub Desktop.
Split an array into chunks and return a number of arrays based on a group size.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Split-ByGroup { | |
<# | |
.SYNOPSIS | |
It will split an array into chunks and return a number of arrays based on a group size | |
.EXAMPLE | |
# first create a sample array (I'm using the RNG class here to do that) | |
$ArraySize = 160 | |
$Array = [byte[]]::new($ArraySize) | |
$rng = [Security.Cryptography.RandomNumberGenerator]::Create() | |
$rng.GetBytes($Array) | |
# and then split it into groups of 50 items each | |
$split = Split-ByGroup -InputArray $Array -GroupSize 50 | |
"Group count: $($split.Count)" | |
"Number of items in last group: $($split[-1].Count)" | |
We create a random array of 160 items, and then we split it up into chunks of 50 items each. | |
We get back 4 groups, the last group has only 10 items, while the other ones have 50. | |
.NOTES | |
This function is much faster than the native Group-Object command | |
Bbut then again the Group-Object is like 2-lines, so depends on your needs | |
#> | |
[CmdletBinding()] | |
param ( | |
$InputArray, | |
[int]$GroupSize = 10, # <-- default group size is 10 items | |
[switch]$Cleanup # <-- optionally run garbage collection at the end | |
) | |
$OutList = [System.Collections.Generic.List[object]]::new() | |
$TmpList = [System.Collections.Generic.List[object]]::new() | |
# add the items to the output list into chunks | |
foreach ($item in $InputArray) { | |
[void]$TmpList.Add($item) | |
if ($TmpList.Count -ge $GroupSize) { | |
[void]$OutList.Add($TmpList.ToArray()) | |
$TmpList.Clear() | |
} | |
} | |
# this is for any left-overs | |
if ($TmpList.Count -gt 0) { | |
[void]$OutList.Add($TmpList.ToArray()) | |
$TmpList.Clear() | |
} | |
Write-Output $OutList.ToArray() -NoEnumerate | |
$OutList.Clear() | |
if ($Cleanup) {[System.GC]::Collect()} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment