I would like to create a new array of strings that dont contain strings from another array. I have it working in the long form. But would like to learn a more Swift way of doing it
The return filteredList would be ["music", "unicorns rainbow walkers"]
let removelist : [String] = ["nerf", "magic beans"]
let originalList : [String] = ["nerf", "music", "unicorns rainbow walkers", "magic beans"]
// tried this but not exactly working
//let filtered = originalList.filter { $0.contains(where: { removelist.contains($0) }) }
// long way
var filtered : [String] = []
for i in 0..<originalList.count {
var isOn = true
for gg in 0..<removelist.count {
if originalList[i].lowercased().contains(removelist[gg].lowercased()){
print(originalList[i])
//filtered = filtered.filter { $0.contains(where: { removelist.contains($0) }) }
isOn = false
}
}
if isOn == true {
filtered.append(originalList[i])
}
}
Is order important? Set or OrderedSet work for this.
import struct Collections.OrderedSet
Array(OrderedSet(originalList).subtracting(removelist))
2 Likes
let removeList = ["nerf", "magic beans"]
let originalList = ["nerf", "music", "unicorns rainbow walkers", "magic beans"]
let removeSet = Set(removeList)
print(originalList.filter { !removeSet.contains($0) })
// '["music", "unicorns rainbow walkers"]'
FYI if removeList is truly known at compile time, it'd probably be better to initialize it as a set
Also, this will not necessarily preserve the order like @anon9791410 's implementation
2 Likes
Both of these are perfect to me! Few lines and make sense. Order is not important as I sort them alphabetically after filtering them.
Thank you both!
1 Like