find the unique elements in two arrays in Go
Code snippet on how to find the unique elements in two arrays in Go
package main
import "fmt"
func main() {
arr1 := []int{1, 2, 4, 5, 6, 7}
arr2 := []int{2, 3, 4, 7, 8}
//to store the unique element
var result []int
//loop to check if arr2 elements are present in arr1
for _, v := range arr2 {
found := false
for _, i := range arr1 {
if v == i {
found = true
break
}
}
//add to the result arr if not found in arr1
if !found {
result = append(result, v)
}
}
fmt.Println(result)
}
This code finds the unique elements in two arrays. First, two arrays, arr1 and arr2, are declared with elements in them. Second, a new array named ‘result’ is declared to store the unique elements. Then, a loop is used to go through each element of array2 and check whether it is present in array1. If it is present, the loop moves to the next value; if the element is not present, it is appended to the result array. Finally, the result array is printed with the unique elements of the two arrays.