Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 309
Octave Avatar asked Oct 21 '25 15:10

Octave


2 Answers

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.

like image 181
Matt Avatar answered Oct 23 '25 08:10

Matt


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)
like image 43
Naigel Avatar answered Oct 23 '25 08:10

Naigel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!