0

I am trying to find out the equivalent of indexof to get the position of specific element in array golang the purpose for integers in array.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("what")

    arr := []int{1, 2, 3, 4, 2, 2, 3, 5, 4, 4, 1, 6}

    i := IndexOf(2, arr)

}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

4 Answers4

2

Write a function. Here's an example assuming that IndexOf returns the first index of the number or -1 if none is found.

// IndexOf returns the first index of needle in haystack
// or -1 if needle is not in haystack.
func IndexOf(haystack []int, needle int) int {
    for i, v := range haystack {
        if v == needle {
            return i
        }
    }
    return -1
}

Run this code on the Go Programming Language Playground.

thwd
  • 46
  • 2
1
package main

import "fmt"

func IndexOf(arr []int, candidate int) int {
    for index, c := range arr {
        if c == candidate {
            return index
        }
    }
    return -1
}

func main() {
    fmt.Println("what")
    arr := []int{1, 2, 3, 4, 2, 2, 3, 5, 4, 4, 1, 6}
    i := IndexOf(arr, 2)
    fmt.Println(i)
}

Add a method IndexOf to search, this is a linear search method.

Ref: https://play.golang.org/p/Hp6Dg--XoIV

sonus21
  • 5,178
  • 2
  • 23
  • 48
1

There is no common library function to do this for you in go.

However if you are using a byte slice, you can use IndexByte(b []byte, c byte) int.

Or you can write a quick function which does this for you:

func indexOf(arr []int, val int) int {
    for pos, v := range arr {
        if v == val {
            return pos
        }
    }
    return -1
}
Ashwin Shirva
  • 1,331
  • 1
  • 12
  • 31
-1

There is no equivalent for IndexOf in Go. You need to implement one your self. But if you have have sorted array of Ints, you can use sort.SearchInts as shown below.

package main

import (
    "fmt"
    "sort"
)

func main() {
    fmt.Println(sort.SearchInts([]int{2,3,4,5,9,10,11}, 5))
}

Also from the godoc:

SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

poWar
  • 745
  • 6
  • 15
  • 1
    This works only if the `arr` is sorted. In that case, it's not necessary to call `sort.IntSlice(arr)` as shown in the ansswer. Because the slice in the question is not sorted, this answer does not apply to the question. – Charlie Tumahai Jun 14 '20 at 06:56
  • Clearly it is evident from his question he is asking for a generic function which does the job. This solution works only for sorted slices. – Ashwin Shirva Jun 14 '20 at 06:58
  • Ok may be i should not have taken the the example from the question above. This was more of a FYI answer. I will edit the code to avoid confusion. – poWar Jun 14 '20 at 07:00