Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten array in PowerShell

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?

like image 412
alex2k8 Avatar asked Apr 02 '09 23:04

alex2k8


People also ask

How do you clear an array in PowerShell?

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 .

How does flattening an array work?

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.


1 Answers

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 
like image 55
Godeke Avatar answered Oct 08 '22 14:10

Godeke