9

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?

David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
  • **See Also**: [Get index of current item in a PowerShell loop](https://stackoverflow.com/q/1785474/1366033) – KyleMit Nov 04 '21 at 20:39

3 Answers3

29

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
  • 194,368
  • 42
  • 353
  • 369
12

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
  • 4,835
  • 4
  • 37
  • 45
2

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
  • 8,067
  • 2
  • 28
  • 47