hkucuk

Find the Difference Between Two Array in GoLang

January 29, 2019 • ☕️ 1 min read • 🏷 computer, software

Translated by author into: DeutschEnglishItalianoРусский


Let’s say we have two arrays. When we want to determine the elements of one of these two arrays that are not in the other array, we need to put these two arrays in a comparison process. Below is a sample function that performs this process in the GoLang programming language.

Sample sequences and the expected output of these arrays are as follows:

array1 := []int8{1, 2, 3, 4, 5}
array2 := []int8{3, 4, 5}

// result
array1 / array2 => {1, 2}

The function of GoLang compares two arrays:

func difference(a, b []int8) []int8 {

    target := map[int8]bool{}
    for _, x := range b {
        target[x] = true
    }

    result := []int8{}
    for _, x := range a {
        if _, ok := target[x]; !ok {
            result = append(result, x)
        }
    }

    return result
}

The process of finding the difference of two arrays:

func main() {
	
    array1 := []int8{1, 2, 3, 4, 5}
    array2 := []int8{3, 4, 5}

    result := difference(array1, array2)
    fmt.Println("array1 / array2 => ", result)
    // output: array1 / array2 =>  [1 2]

    result2 := difference(array2, array1)
    fmt.Println("array2 / array1 => ", result2)
    // output: array2 / array1 =>  []
}

To test the code running => RUN