I'm new to swift and programming in general. I have multiple arrays of names in a database and I need to check for same names in these arrays. I've found some solutions to compare two arrays, but not multiple so I wrote some additional code. But performance wise it's not the best practice I think. And also not the best way to add first all the names and then remove the duplicates..
Does anyone has any better ideas/solutions for my problem?
Code:
import UIKit
let array1 = ["Max", "Peter","Kathrin", "Sara", "Kirsten", "Mike", "Elon"] // Peter, Kathrin, Mike, Sara
let array2 = ["Pamela", "Chris", "James", "Sebastian", "Mike"] // Mike, Chris
let array3 = ["John", "Daniel", "Susan", "Mathias", "Mike", "Donald"] // Mike
let array4 = ["Tim", "Kathrin", "Alan", "Chris", "Amy", "Sara"] // Kathrin, Chris
let array5 = ["Cara", "Charly", "Emily", "Maja", "Peter", "Sara"] // Peter, Sara
// Output should be: Peter, Kathrin, Mike, Sara, Chris
var array = [Array<String>]()
array.append(array1)
array.append(array2)
array.append(array3)
array.append(array4)
array.append(array5)
var names = [String]()
for i in 0...array.count - 2 {
for z in 1...array.count - 1 {
if z + i < array.count {
let commonElements = Array(Set(array[i]).intersection(Set(array[z+i])))
names.append(contentsOf: commonElements)
}
}
}
print(names.removeDuplicates())
Extension:
extension Array where Element: Hashable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
question from:https://stackoverflow.com/questions/65646309/compare-multiple-arrays-for-same-elements-in-swift