I have an array of strings which are airport codes something like this,
let list = [ "JFK-ATL-CDG-JFK",
"HKG-MIA-NRT",
"LAX-DFW-FRA-CDG-AMS-FRA-DFW",
"PEK-SEA-MCO-YYZ-SEA",
"MSP-DTW-BKK"]
What I want to do is return only the strings which has duplicate airport codes, so if a user visits the same city again then I would like that string to be returned in an array like this.
let updatedList = [ "JFK-ATL-CDG-JFK",
"LAX-DFW-FRA-CDG-AMS-FRA-DFW",
"PEK-SEA-MCO-YYZ-SEA"]
Second and third element in the array does not have duplicate codes so those are not returned in the new array, Notice that airport codes are separated by "-" does Swift provide a way to remove "-" and add them back? what is the easiest way to do this. Thanks.
you could try something simple like this, works for me:
let list = [ "JFK-ATL-CDG-JFK",
"HKG-MIA-NRT",
"LAX-DFW-FRA-CDG-AMS-FRA-DFW",
"PEK-SEA-MCO-YYZ-SEA",
"MSP-DTW-BKK"]
var updatedList: [String] = []
list.forEach { item in
let test = item.split(separator: "-").map{String($0)}
if test.count != Set(test).count {
updatedList.append(item)
}
}
print("\n---> updatedList: \(updatedList) \n")
Or, more succinctly:
let updatedList: [String] = list.compactMap{ item in
let arrTest = item.split(separator: "-").map{String($0)}
return arrTest.count != Set(arrTest).count ? item : nil
}