Golang : Find commonalities in two slices or arrays example
Problem:
You have two slices of the same length and you want to find out if they have similar/common items.
Solution :
- Iterate items of the first slice.
- Get the index number.
- Use the index number to get the second slice item.
- Compare the items.
- If similar or common, then add the item to a new slice.
- Loop until no more item in the first slice.
Here you go!
package main
import (
"fmt"
)
// NOTE : This example will only work if the length of slice a == length of slice b
// In production, make sure to check the length and capacity of the slices
// before comparing.
func main() {
a := []string{"Hello", "No", "Cheers"}
fmt.Println("Slice a : ", a)
b := []string{"Hello", "Yes", "Cheers"}
fmt.Println("Slice b : ", b)
// compare a to be and find common items
// and store into c
c := []string{}
for i := range a {
if a[i] == b[i] {
c = append(c, a[i])
}
}
fmt.Println("Common items : ", c)
// compare a to be and find item not in a
// and store into d
d := []string{}
for i := range a {
if a[i] != b[i] {
d = append(d, a[i])
}
}
fmt.Println("Item that a has over b ", d)
// compare a to be and find item not in b
// and store into e
e := []string{}
for i := range b { // iterate b instead of a
if a[i] != b[i] {
e = append(e, b[i])
}
}
fmt.Println("Item that b has over a ", e)
}
Output :
Slice a : [Hello No Cheers]
Slice b : [Hello Yes Cheers]
Common items : [Hello Cheers]
Item that a has over b [No]
Item that b has over a [Yes]
NOTES: This example will only work if the length of slice a == length of slice b. In production, make sure to check the length and capacity of the slices before comparing.Otherwise, you will get panic: runtime error: index out of range
error.
References :
See also : Golang : How to count duplicate items in slice/array?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.7k Golang : Inject/embed Javascript before sending out to browser example
+13.3k Golang : Activate web camera and broadcast out base64 encoded images
+8.9k Golang : does not implement flag.Value (missing Set method)
+9.2k Golang : Extract or copy items from map based on value
+10.3k Golang : Get local time and equivalent time in different time zone
+7.1k Golang : Individual and total number of words counter example
+32.7k Delete a directory in Go
+4.4k Mac OSX : Get disk partitions' size, type and name
+13.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+4.7k Golang : Calculate a pip value and distance to target profit example
+20k nginx: [emerg] unknown directive "passenger_enabled"
+3.4k Golang : Switch Redis database redis.NewClient