David.Chu.ca
David.Chu.ca

Reputation: 38654

PS: Get index in an array list

I have an array of strings. Not sure if there is simple way to get the index of an item first found in the array?

# example array
$array = "A", "B", "C"
$item = "B"
# the following line gets null, any way to get its index?
$index = $array | where {$_ -eq $item} | ForEach-Object { $_.Index }

I could do it in a loop. not sure if there is any alternative way?

Upvotes: 10

Views: 52582

Answers (3)

Keith Hill
Keith Hill

Reputation: 201672

If you know that the value occurs only once in the array, the [array]::IndexOf() method is a pretty good way to go:

$array = 'A','B','C'
$item = 'B'
$ndx = [array]::IndexOf($array, $item)

Besides being terse and to the point, if the array is very large the performance of this approach is quite a bit better than using a PowerShell cmdlet like Where-Object. Still, it will only find the first occurrence of the specified item. But you can use the other overload of IndexOf to find the next occurrence:

$ndx = [array]::IndexOf($array, $item, $ndx+1)

$ndx will be -1 if the item isn't found.

Upvotes: 29

Start-Automating
Start-Automating

Reputation: 8367

Using Where-Object is actually more likely to be slow, because it involves the pipeline for a simple operation.

The quickest / simplest way to do this that I know of (in PowerShell V2) is to assign a variable to the result of a for

$needle = Get-Random 100
$hayStack = 1..100 | Get-Random -Count 100
$found = for($index = 0; $index -lt $hayStack.Count; $index++) {
    if ($hayStack[$index] -eq $needle) { $index; break } 
}
"$needle was found at index $found"

Upvotes: 2

Peter Seale
Peter Seale

Reputation: 5015

Use a for loop (or a foreach loop that iterates over the array index...same difference). I don't know of any system variable that holds the current array index inside a foreach loop, and I don't think one exists.

# example array
$array = "A", "B", "C"
$item = "B"
0..($array.Count - 1) | Where { $array[$_] -eq $item }

Upvotes: 13

Related Questions