I need to create an array from multiple arrays. The new array must only contain the values that is present in all arrays passed in. For example.
array1 := []string{"hello", "germany", "brasil", "fiji"}
array2 := []string{"goodbye", "germany", "brasil", "fiji"}
array3 := []string{"hello", "brasil", "fiji"}
array4 := []string{"hello", "brasil", "fiji", "usa"}
func mergeArrays(arrs ...[]string) []string{
// process arrays
}
myNewArray := mergeArrays(array1,array2,array3,array4)
fmt.Println(myNewArray) // ["fiji", "brasil"]
The example should return ["fiji", "brasil"]
since they are the only values present in all arrays.
How could I go about writing a function that could achieve such a goal in golang?
This is my attempt but feels a bit clumsy
func mergeArrays(arrs ...[]string) []string {
var finalArr []string
if len(arrs) == 0 {
return finalArr
}
for i, a := range arrs {
if i == 0 {
finalArr = arrs[0]
continue
}
for i, e := range finalArr {
if !strContains(a, e) {
finalArr = append(finalArr[:i], finalArr[i+1:]...)
}
}
}
return finalArr
}
func strContains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
Playground link: https://play.golang.org/p/KRygw7OVBbn