So I've got a long list of strings that I am arranging into 'chunks' of (say) 10. So the data structure for that is an array of 'chunks' where each 'chunk' is an array of up to 10 strings. So you can imagine it like this:
Chunk Array
-----------
a,b,c,d,e,f,g,h,i,j <-- an array of 10 strings
h,i,j,k,l,m,n,o,p,q <-- an array of 10 strings
r,s,t <-- an array of 3 strings
^ So this is an array of three 'chunks'
I have a function that takes in a long list and outputs an array of chunks as above. The function is from here and for most cases it works well.
function ChunkBy($items,[int]$size) {
$list = new-object System.Collections.ArrayList
$tmpList = new-object System.Collections.ArrayList
foreach($item in $items) {
$tmpList.Add($item) | out-null
if ($tmpList.Count -ge $size) {
$list.Add($tmpList.ToArray()) | out-null
$tmpList.Clear()
}
}
if ($tmpList.Count -gt 0) {
$list.Add($tmpList.ToArray()) | out-null
}
return $list.ToArray()
}
The problem is that if you call the function with a small list that will result in only one 'chunk', powershell flattens the outer array, so instead of an array containing one 'chunk', you get a flat array of strings.
Here's a little helper function to write the chunk structure to the console:
function ShowChunks($items)
{
Write-Output " "
Write-Output "array has $($items.Length) chunks"
Write-Output "-----------------"
foreach($c in $items)
{
[system.String]::Join(",", $c)
}
}
And here's some test code to demonstrate the problem, using the two functions above
$testArray = ("a","b","c","d","e")
$res1 = ChunkBy $testArray 3
ShowChunks $res1
$res2 = ChunkBy $testArray 6
ShowChunks $res2
$res1 is fine. But for $res2 this gives:
array has 5 chunks
-----------------
a
b
c
d
e
But really what I want is:
array has 1 chunks
-----------------
a,b,c,d,e
So to summarise, the problem is:
I've got a function that returns an 'Array of Arrays', but when there's only one Array to return, instead of an 'Array of one Array', I just get an 'Array'.
This happens because of Powershells tendancy to flatten one-element arrays into just an element. How can we fix it?