arrays - Compare two slices and delete the unique values in Golang -


i have not working :

var int var names = []string{"f5", "f7", "c6", "h5", "g5"} var board = []string{"b4", "d4", "g5", "f5", "f7", "c6"}  = 0; < len(names)-1; i++ {     k := 0; k < len(board)-1; k++ {         if names[i] != board[k] {             names = append(names[:i], names[i+1:]...)         }     } } fmt.printf("%s ", names[i]) 

you need intersection of 2 slices (delete unique values first slice), try working sample code (and notice i++):

package main  import "fmt"  func main() {     names := []string{"f5", "f7", "c6", "h5", "g5"}     board := []string{"b4", "d4", "g5", "f5", "f7", "c6"}     := 0; < len(names); {         exist := false         _, b := range board {             if b == names[i] {                 exist = true                 break             }         }         if !exist {             names = append(names[:i], names[i+1:]...) // delete names[i]         } else {             i++         }     }     fmt.println(names) // [f5 f7 c6 g5] } 

output:

[f5 f7 c6 g5] 

also may use intersection of 2 slices new result, try working sample code:

package main  import "fmt"  func main() {     names := []string{"f5", "f7", "c6", "h5", "g5"}     board := []string{"b4", "d4", "g5", "f5", "f7", "c6"}     result := make([]string, 0, 11)     _, v := range names {         exist := false         _, w := range board {             if v == w {                 exist = true                 break             }         }         if exist {             result = append(result, v)         }     }     fmt.println(result) // [f5 f7 c6 g5] } 

output:

[f5 f7 c6 g5] 

or if need union of 2 slices, try working sample code:

package main  import "fmt"  func main() {     names := []string{"f5", "f7", "c6", "h5", "g5"}     board := []string{"b4", "d4", "g5", "f5", "f7", "c6"}     _, b := range board {         exist := false         _, n := range names {             if n == b {                 exist = true                 break             }         }         if !exist {             names = append(names, b)         }     }     fmt.println(names) // [f5 f7 c6 h5 g5 b4 d4] } 

output:

[f5 f7 c6 h5 g5 b4 d4] 

Comments