10

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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

13

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 }

1 Comment

Nice. If there are two "B"s in the array, the result will be an array of index values.
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.