# A scalable way to remove duplicates from Arrays without extensions in Swift 4

This method is an attempt at removing duplicates from arrays without the use of extensions.

func arrayWithDuplicatesRemoved<T: Equatable>(from array: [T]) -> [T] {
var results = [T]()
return array.compactMap { (element) -> T? in
if results.contains(element) {
return nil
} else {
results.append(element)
return element
}
}
}

let dirty = ["apple", "kiwi", "grapefruit", "kiwi", "kiwi", "strawberry", "watermelon", "apple", "banana"]
let clean = arrayWithDuplicatesRemoved(from: dirty)
print(clean) // ["apple", "kiwi", "grapes", "strawberry", "watermelon", "banana"]

• Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. – Sᴀᴍ Onᴇᴌᴀ Nov 15 '18 at 19:16

Your algorithm is O(n^2) so not very scalable... The immediate improvement I can think of is to use a Set for results (which means making T Hashable).

If you aren't worried about position, then just create a Set from an array and you are done.

• In this case I'm not worried about order, thanks for the help. – bsod Nov 15 '18 at 18:55

UPDATE

The original was not the most scalable; nesting how I did meant that the square of the size of the argument is how performance is measured (thanks to Daniel T. for pointing that out). This is much more scalable as performance is not entirely linear but much closer than before.

func ArrayWithDuplicatesRemovedFrom<T: Hashable>(array: [T]) -> [T] {
return Array(Set(array))
}