Removing duplicate elements from an array in Swift

后端 未结 30 2004
遥遥无期
遥遥无期 2020-11-22 00:07

I might have an array that looks like the following:

[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

Or, reall

30条回答
  •  无人共我
    2020-11-22 00:35

    1. First add all the elements of an array to NSOrderedSet.
    2. This will remove all the duplicates in your array.
    3. Again convert this orderedset to an array.

    Done....

    Example

    let array = [1,1,1,1,2,2,2,2,4,6,8]
    
    let orderedSet : NSOrderedSet = NSOrderedSet(array: array)
    
    let arrayWithoutDuplicates : NSArray = orderedSet.array as NSArray
    

    output of arrayWithoutDuplicates - [1,2,4,6,8]

提交回复
热议问题