16

Assume there is an array in variable $a that is created like this,

$a  = ,@(1,2,3)
$a += ,@(4,5,6)
$a += ,@(7,8,9)
$a += ,@(10,11,12)

I want to extract part of the array, say $a[1] and $a[2], into another variable, say, $b such that,

$b[0] = @(4,5,6)
$b[1] = @(7,8,9)

I can use a simple for loop to do the task, but I am thinking if there is a more 'elegant' way to do this... may be a one-liner?

Thanks in advance.

2 Answers 2

34

You can use the Range operator to slice the array:

$b = $a[1..2]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. You made it so easy. :)
4

It is worth noting the Range operator supports dynamic values - very useful when you want to work out your range dynamically, for example:

$a = @(0,1,2,3,7)
$b = @(4,5,6)
$twotoseven = $a[($a.Length-($a.Length-2))..($a.Length-2)] + $b + $a[-1]

Output:

2 3 4 5 6 7

Comments

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.