How to Flatten an Array in PowerShell (With Example)


Often you may want to flatten a nested array in PowerShell.

You can use the following basic syntax to do so:

$flat_array = @($nested_array | ForEach-Object {$_})

This particular example flattens the nested array named $nested_array into a new array named $flat_array.

This method works by piping the nested array into a ForEach-Object loop in which we simply return the values ($_) from each inner array.

We then we wrap the whole thing with the @ symbol to force the output to be an array.

The following example shows how to use this syntax in practice.

Example: How to Flatten an Array in PowerShell

Suppose we create the following nested array named $nested_array:

$nested_array = @(1, 2, 3, @(4, 5, @(6)))

The following screenshot shows how to use this syntax in practice:

Now suppose that we would like to flatten this array into a new array.

We can use the following syntax to do so:

$flat_array = @($nested_array | ForEach-Object {$_})

The following screenshot shows how to use this syntax in practice:

PowerShell flatten array

Notice that the new array named $flat_array contains all of the values from the nested array in a single array.

Once we’ve created this flat array, we can perform operations on it just like we would with an ordinary one-dimensional array.

For example, we can use the count property to get the total number of values in the array:

The output tells us that there are 6 total values in the array.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array of Arrays
PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply