I have two slices:
slice1 := []string{"a", "b", "c", "d"}
slice2 := []string{"c", "d", "e", "f"}
Expected result:
[]string{"c", "d"}
What's the best way to create a slice from duplicate items of slice1
and slice2
with this specifications:
- Minimum code
- Slices are large
- Slices are not sorted
- Do not modify the slices
- They may not contain the duplicates
This is what I have tried:
slice1 := []string{"a", "b", "c", "d"}
slice2 := []string{"c", "d", "e", "f"}
duplicateItems := []string{}
for _, item1 := range slice1 {
for _, item2 := range slice2 {
if item1 == item2 {
duplicateItems = append(duplicateItems, item1)
}
}
}
fmt.Println(duplicateItems) // [c d]