tags:

views:

108

answers:

3

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?

+1  A: 

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 }
Peter Seale
Nice. If there are two "B"s in the array, the result will be an array of index values.
David.Chu.ca
+1  A: 

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"
Start-Automating
+3  A: 

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.

Keith Hill