Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: how to fetch a single column from a multi-dimensional array?

Is there a function, method, or language construction allowing to retrieve a single column from a multi-dimensional array in Powershell?

$my_array = @()
$my_array += ,@(1,2,3)
$my_array += ,@(4,5,6)
$my_array += ,@(7,8,9)

# I currently use that, and I want to find a better way:
foreach ($line in $my_array) {
    [array]$single_column += $line[1]    # fetch column 1
}
# now $single_column contains only 2 and 5 and 8

My final goal is to find non-duplicated values from one column.

like image 307
Gregory MOUSSAT Avatar asked Oct 16 '25 13:10

Gregory MOUSSAT


2 Answers

Sorry, I don't think anything like that exist. I would go with:

@($my_array | foreach { $_[1] })

To quickly find unique values I tend to use hashtables keys hack:

$UniqueArray = @($my_array | foreach -Begin { 
    $unique = @{} 
} -Process { 
    $unique.($_[1]) = $null
} -End { 
    $unique.Keys 
})

Obviously it has it limitations...

like image 127
BartekB Avatar answered Oct 19 '25 07:10

BartekB


To extract one column:

$single_column = $my_array | foreach { $_[1] }

To extract any columns:

$some_columns = $my_array | foreach { ,@($_[2],$_[1]) }   # any order

To find non-duplicated values from one column:

$unique_array = $my_array | foreach {$_[1]} | sort-object -unique
# caveat: the resulting array is sorted,
# so BartekB have a better solution if sort is a problem
like image 23
Gregory MOUSSAT Avatar answered Oct 19 '25 06:10

Gregory MOUSSAT



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!