Octave
Octave

Reputation: 43

powershell sort multidimensional array

I am a newbie in Powershell, but this is driving me a bit crazy. I have looked at various questions here, but could not find an answer so here I go. Apologies if this has been covered already.

I have two text files containing columns of numbers. I would like to create an array containing those 2 columns and sort it by column 1 or 2.

If we had

$a=@(1,5,10,15,25)
$b=@(100,99,98,99,10)

we create

c$=$a,$b

My initial thought was to try something like this:

$c | sort { [int]$_[0] }

But it does not work. I have tried many different things so any advice would be appreciated.

I am editing this as my question was not so clear. Ultimately, if I sort $c by ascending column 2, I expect something like:

25,10
10,98
5,99
15,99
1,100

Any idea how to achieve this ?

Upvotes: 4

Views: 12994

Answers (2)

Matt
Matt

Reputation: 46710

I am not sure about how you have declared your dimensional array because it is like you want it to be declared like this or something similar

$c = @(@(1,100),@(5,99),@(10,98),@(15,99),@(25,10))

If it was in that state then sorting is a breeze

$c | Sort-Object @{Expression={$_[1]}; Ascending=$True} | %{
    "$($_[0]),$($_[1])"
}

Sort-Object works well with one dimensional arrays. When multiple properties are involved you need to specify which property to sort on to get the expected output. Since there are none we use a calculated expression to make on base on the second "column".

Sample Output

25,10
10,98
5,99
15,99
1,100

If you really want to work with your arrays like that we need an intermediate step to convert what you have to how it can be sorted the way you expect.

$a=@(1,5,10,15,25)
$b=@(100,99,98,99,10)
$c = @()
for($i = 0;$i -lt $a.Count; $i++){
    $c += ,@($a[$i],$b[$i])
}

After running this code $c will work just like it does with my sorting.

Upvotes: 5

Naigel
Naigel

Reputation: 9644

Welcome to powershell world. The syntax is slightly different from classical programming languages, usually cmdlets take their input from current pipeline. In this case the command you talk about is Sort-Object and you can use it directly with the pipe content where you have the array content

$c = ($a | Sort-Object), ($b | Sort-Object)

Upvotes: 1

Related Questions