Assume we have:
$a = @(1, @(2, @(3)))
I would like to flatten $a
to get @(1, 2, 3)
.
I have found one solution:
@($a | % {$_}).count
But maybe there is a more elegant way?
delete element It's not easy to delete array element in PowerShell. Array data structure is not designed to change size. Instead of delete, just replace the value with $null .
To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.
Piping is the correct way to flatten nested structures, so I'm not sure what would be more "elegant". Yes, the syntax is a bit line-noisy looking, but frankly quite serviceable.
2020 Edit
The recommended syntax these days is to expand %
to ForEach-Object
. A bit more verbose but definitely more readable:
@($a | ForEach-Object {$_}).count
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