OneBite.Dev - Coding blog in a bite size

find the common elements in two arrays in Go

Code snippet on how to find the common elements in two arrays in Go

  package main
  
  import "fmt"
  
  func commonElements(array1, array2 []int) []int {
      var commonElements []int
      for _, v1 := range array1 {
          for _, v2 := range array2 {
              if v1 == v2 {
                  commonElements = append(commonElements, v1)
              }
          }
      }
      return commonElements
  }
  
  func main() {
      array1 := []int{2, 5, 7, 9, 11}
      array2 := []int{5, 7, 11, 13, 15}
      result := commonElements(array1, array2)
      fmt.Println(result)
  }

This code checks for common elements between two arrays. First, two arrays are created with the names array1 and array2. A loop then iterates through each array and checks to see if the elements in each are the same. If they are, the element is added to an empty array called commonElements. The function then returns the commonElements array. Finally, the main function is called, which prints out the result of the commonElements function.

go