Array can be any type like
let myArray1 = [ 1, 2, 3, 1, 2, 1, 3, nil, 1, nil]
let myArray2 = [ 1, 2.0, 1, 3, 1.0, nil]
After removing duplicate values from the array, the new array should be:
Output -
[ 1, 2, 3, nil ]
Ahmad F
31.8k19 gold badges100 silver badges150 bronze badges
asked Jan 17, 2018 at 9:33
-
1please check related questions : stackoverflow.com/questions/25738817/…Sharad Chauhan– Sharad Chauhan2018年01月17日 09:35:25 +00:00Commented Jan 17, 2018 at 9:35
-
1i tried this link as well stackoverflow.com/questions/25738817/…Pratik Panchal– Pratik Panchal2018年01月17日 09:36:23 +00:00Commented Jan 17, 2018 at 9:36
-
in my array i have nil value as wellPratik Panchal– Pratik Panchal2018年01月17日 09:36:51 +00:00Commented Jan 17, 2018 at 9:36
-
Do you want to keep the initial ordering of the Array?David Pasztor– David Pasztor2018年01月17日 09:37:56 +00:00Commented Jan 17, 2018 at 9:37
-
yes i manage ordering alsoPratik Panchal– Pratik Panchal2018年01月17日 09:38:50 +00:00Commented Jan 17, 2018 at 9:38
3 Answers 3
@Daniel's solution as a generic function:
func uniqueElements<T: Equatable>(of array: [T?]) -> [T?] {
return array.reduce([T?]()) { (result, item) -> [T?] in
if result.contains(where: {0ドル == item}) {
return result
}
return result + [item]
}
}
let array = [1,2,3,1,2,1,3,nil,1,nil]
let r = uniqueElements(of: array) // [1,2,3,nil]
answered Jan 17, 2018 at 10:14
Sign up to request clarification or add additional context in comments.
2 Comments
Pratik Panchal
Alternate is that possible using extension of sequence.?
Gereon
Would be interested to see that myself, I haven't found a way to express this so far.
You can use this reduce to remove duplicated entries:
myArray.reduce([Int?]()) { (result, item) -> [Int?] in
if result.contains(where: {0ドル == item}) {
return result
}
return result + [item]
}
output: [1, 2, 3, nil]
answered Jan 17, 2018 at 9:51
2 Comments
Pratik Panchal
type is not specify it can be dynamic like int, double or it can be String of array
Pratik Panchal
Array can be Any Type like 1) let myArray1 = [1,2,3,1,2,1,3,nil,1,nil] or 2) let myArray2 = [1,2.0,1,3,1.0,nil]
Please check this code, I have used NSArray after getting filtered array you can convert into swift array
let arr = [1, 1, 1, 2, 2, 3, 4, 5, 6, nil, nil, 8]
let filterSet = NSSet(array: arr as NSArray as! [NSObject])
let filterArray = filterSet.allObjects as NSArray //NSArray
print("Filter Array:\(filterArray)")
answered Jan 17, 2018 at 10:12
1 Comment
Gereon
This does not preserve the order of elements.
lang-swift