Slicing a jagged array in both dimensions

Let's say I create a simple square jagged array and want to extract a square part of it (e.g., M[0][0], M[0][1], M[1][0], M[1][1]. What would be the best way to slice along the first index? The below code:

$M=@(@(1,2,3),@(4,5,6),@(7,8,9))
Write-Host $M[0][0..1] # answer = 1 2
Write-Host $M[1][0..1] # answer = 4 5

Produces desired results. But one apparently cannot slice wrt the first index:

Write-Host $M[0..1][0] # answer = 1 2 3
Write-Host $M[0..1][1] # answer = 4 5 6
Write-Host $M[0..1][0..1] # answer = 1 2 3 4 5 6

What is the simplest way to get a desired slice M[0..1][0..1] returning "1 2 4 5"?

Thanks for help.

Posted May 9, 2025, 12:57 PM UTC

106

Comments aren't archived yet

This post had 6 comments on Reddit. Comments for this period haven't been loaded into the archive yet.