C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Set: The "encountered" set is used to record strings that have been seen. We use contains to see if a string has been added.
Result: This starts as an empty string array. We add elements with append() as we proceed in the for-in loop.
Thus: We only add elements that have not been added to the set. We append() and insert() those elements as we encounter them.
Swift program that removes duplicates from string array
func removeDuplicates(array: [String]) -> [String] {
var encountered = Set<String>()
var result: [String] = []
for value in array {
if encountered.contains(value) {
// Do not add a duplicate element.
}
else {
// Add value to the set.
encountered.insert(value)
// ... Append the value.
result.append(value)
}
}
return result
}
// Test this array of animal names.
let animals: [String] = ["bird", "cat", "cat", "fish", "bird"]
print(animals)
// Call the method to dedupe the string array.
let dedupe = removeDuplicates(array: animals)
print(dedupe)
Output
["bird", "cat", "cat", "fish", "bird"]
["bird", "cat", "fish"]
Set: We use the set initialization func to make a set of unique elements from the Int array.
Result: The set converted back into an array. Only unique elements are in this array.
ArraySwift program that removes duplicate integers
func removeDuplicateInts(values: [Int]) -> [Int] {
// Convert array into a set to get unique values.
let uniques = Set<Int>(values)
// Convert set back into an Array of Ints.
let result = Array<Int>(uniques)
return result
}
// Remove duplicates from these example numbers.
let numbers: [Int] = [10, 20, 20, 30, 40, 50, 10]
let uniqueNumbers = removeDuplicateInts(values: numbers)
print(numbers)
print(uniqueNumbers)
Output
[10, 20, 20, 30, 40, 50, 10]
[50, 10, 20, 30, 40]
Here: We filter out all elements that do not equal "red" in the array. We have two strings in the result, so there is a duplicate "red."
Note: This code does not remove duplicates. But it can be used to detect or report errors on dupes.
Swift program that filters elements
let colors = ["red", "orange", "red", "blue"]
// Use filter to get all elements by value.
let filtered = colors.filter { (x) -> Bool in
x == "red"
}
// Display results.
print(filtered)
// When this count is 1, we have a distinct element (no dupes).
print(filtered.count)
Output
["red", "red"]
2