You are matching your array items by their prefix
(first 2 letters). This is a little more complicated than the usual situation of handling duplicate values.
Here is a straightforward approach that uses a Set
to keep track of the prefixes that have been seen while building the result
array:
let arr = ["9s 0.4", "Jh 0.9", "8d 0.8", "8d 0.6", "5d 0.9", "3h 0.7", "9s 0.3", "2c 0.9", "As 0.7"]
// keep track of the prefixes we have seen
var prefixes = Set<String>()
// array to hold the results
var result = [String]()
for value in arr {
// get the prefix for this value
let prefix = String(value.prefix(2))
// is this a new prefix?
if !prefixes.contains(prefix) {
// new prefix, so add value to new array
result.append(value)
// add prefix to our set
prefixes.insert(prefix)
}
}
print(result)
["9s 0.4", "Jh 0.9", "8d 0.8", "5d 0.9", "3h 0.7", "2c 0.9", "As 0.7"]
Functional Approach: Use filter
with Set
.inserted
(As @LeoDabus demonstated in this answer, you can use a Set
with filter
to remove custom duplicates)
You can do this with a functional approach which works in very much the same way as the approach shown above. It uses a Set
to keep track of the prefixes
seen and .inserted
to decide if a new prefix
was added to the Set
. In the cases where a new prefix
was added to prefixes
, filter
selects the item to be in the new results
array.
let arr = ["9s 0.4", "Jh 0.9", "8d 0.8", "8d 0.6", "5d 0.9", "3h 0.7", "9s 0.3", "2c 0.9", "As 0.7"]
var prefixes = Set<Substring>()
let result = arr.filter { prefixes.insert($0.prefix(2)).inserted }
print(result)
["9s 0.4", "Jh 0.9", "8d 0.8", "5d 0.9", "3h 0.7", "2c 0.9", "As 0.7"]
(source: S) -> [T] { var buffer = [T]() var added = Set()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60] – Rebai Ahmed Aug 10 '19 at 11:56