How to delete duplicates from an integer array?

How can I write a function which deletes the duplicates from an integer array ?
Answered by Claude31 in 631547022
Here is a brute force solution:

Code Block
let originalArray = [1, 3, 6, 1, 2]
var strippedArray : [Int] = []
for item in originalArray {
if !strippedArray.contains(item) {
strippedArray.append(item)
}
}
print(strippedArray)


You can make it generic:
Code Block
func strip<T:Equatable>(_ array: [T]) -> [T] {
var stripped : [T] = []
for item in array {
if !stripped.contains(item) {
stripped.append(item)
}
}
return(stripped)
}
strippedArray = strip(originalArray)
print(strippedArray)


If you don't mind loosing the order of the original array:
Code Block
strippedArray = Array(Set(originalArray))

Accepted Answer
Here is a brute force solution:

Code Block
let originalArray = [1, 3, 6, 1, 2]
var strippedArray : [Int] = []
for item in originalArray {
if !strippedArray.contains(item) {
strippedArray.append(item)
}
}
print(strippedArray)


You can make it generic:
Code Block
func strip<T:Equatable>(_ array: [T]) -> [T] {
var stripped : [T] = []
for item in array {
if !stripped.contains(item) {
stripped.append(item)
}
}
return(stripped)
}
strippedArray = strip(originalArray)
print(strippedArray)


If you don't mind loosing the order of the original array:
Code Block
strippedArray = Array(Set(originalArray))

Did this answer your question ?
Yes man, thank you very much!!!
How to delete duplicates from an integer array?
 
 
Q