0

I have an array with fields (a multi dimensional array, if I am correct), my aim is to create another array based on elements filtered from the first.

However when I come to deference $arr2 by looking at its first element $arr[0], I get the error message:

Cannot index into a null array

Can someone please provide me with some advise as to the most elegant way of resolving this.

for ($i=0; $i -lt $arr1.length; $i++) {
    if ($arr1[$i].source -eq $SomeValue) {
        $arr2 += @( $arr1[$i] )
    }
}
2
  • I guess that's because you haven't initialized $arr2 anywhere. Trying putting $arr2 = @() at the top of your code. Commented May 29, 2018 at 13:00
  • 1
    Personally I may need a little more information to completely understand your situation. First, based on your code, $arr1 is an array of objects. Not a multi-dimensional array. Second, what is the goal of forcing elements to be added to $arr2 as arrays instead of simply adding the element as it is $arr2 += $arr1[$i]? Commented May 29, 2018 at 13:01

1 Answer 1

1

$arr2 = @( $arr1 | Where { $_.source -eq $someValue } )

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I went with in the end $arr1 = < call function to generate array of objects > $arr2 = $arr1.where({ ([string]$_.Source) -eq $FilterString })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.