Gregory MOUSSAT
Gregory MOUSSAT

Reputation: 872

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.

Upvotes: 4

Views: 20600

Answers (3)

Sabarish
Sabarish

Reputation: 11

I tried @BartekB's solution and it worked for me. But for the unique part I did the following.

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

I am not very familiar with powershell but I am posting this hoping it helps others since it worked for me.

Upvotes: 1

Gregory MOUSSAT
Gregory MOUSSAT

Reputation: 872

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

Upvotes: 2

BartekB
BartekB

Reputation: 8660

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...

Upvotes: 5

Related Questions