Monthly Archive

Categories

Reverse an array

Ever needed to reverse an array?

If its sorted then sorting in the opposite direction will work. Most arrays aren’t sorted so you need to use the Reverse static method of the array class

 

Here’s some examples

$carray = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
$carray -join ','
[array]::Reverse($carray)
$carray -join ','

 

$iarray = 1,2,3,4,5,6,8,9,10
"$iarray"
[array]::Reverse($iarray)
"$iarray"

 

$psa = Get-Process p*
$psa
[array]::Reverse($psa)
$psa

 

The thing to note is that the array is reversed rather than creating output so if you do this

$iarray = 1,2,3,4,5,6,8,9,10
$newary = [array]::Reverse($iarray)

$iarray is reversed and $newary is empty!

 

If you need the original and reversed arrays take a copy of the original and then reverse one of them.

Comments are closed.