I want to create an empty array of arrays in Powershell to hold "tuples" of values (arrays are immutable).
Therefore I try something like:
The type of $arr
is Object[]
. I've read that += @(1,2)
appends the given element (i.e. @(1,2)
) to $arr
(actually creates a new array). However, in this case it seems that the arrays are concatenated, why?
$arr = @()
$arr += @(1,2)
$arr.Length // 2 (not 1)
If I do as follows, it seems that $arr
contains the two arrays @(1,2),@(3,4)
, which is what I want:
$arr = @()
$arr += @(1,2),@(3,4)
$arr.Length // 2
How do I initialize an empty array of arrays, such that I can add one subarray at a time, like $arr += @(1,2)
?
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 .
1) Assigning it to a new empty array This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.
Array Initializer To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.
The answer from Bruce Payette will work. The syntax seems a bit awkward to me, but it does work. At least it is not Perl.
Another way to do this would be with an ArrayList
. To me, this syntax is more clear and more likely to be understood by another developer (or myself) in six months.
[System.Collections.ArrayList]$al = @()
$al.Add(@(1,2))
$al.Add(@(3,4))
foreach ($e in $al) {
$e
$e.GetType()
}
As far as I can tell, you can't do it natively in PowerShell, nor can you do it with the [System.Array]
type. In both cases, you seem to need to define both the length and the type of the array. Because I wanted a completely empty array of arrays, with the ability to store any type of value in the array, I did it this way.
$x=[System.Collections.ArrayList]::new()
$x.Count
$x.GetType()
$x.Add([System.Collections.ArrayList]::new()) > $null
$x.Count
$x[0].Count
$x[0].GetType()
$x[0].Add("first element") > $null
$x.Count
$x[0].Count
$x[0][0]
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