Created
July 12, 2018 05:14
-
-
Save DineshKachhot/ba82a4d1a10036d739ef725eea44ee2a to your computer and use it in GitHub Desktop.
Array extension to return the unique list of objects based on a given key.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
func unique<T:Hashable>(by: ((Element) -> (T))) -> [Element] { | |
var set = Set<T>() //Keep unique list in a Set for fast retrieval | |
var orderedArray = [Element]() //Keeping the unique list of elements but ordered | |
for value in self { | |
if !set.contains(by(value)) { | |
set.insert(by(value)) | |
orderedArray.append(value) | |
} | |
} | |
return orderedArray | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage Example...
let uniqueBasedOnName = results.unique{$0.name}