[Solved] Using Swift Get array of non repeating numbers from array of numbers


You may try the following:

let numArray = [1, 2, 3, 3, 4, 5, 5]

// Group by value
let grouped = Dictionary(grouping: numArray, by: { $0 })

// Filter by its count, convert back to Array and sort
let unique = Array(grouped.filter { $1.count == 1 }.map(\.key)).sorted()

print(unique) // [1, 2, 4]

Here is an alternative way without using higher order functions:

let numArray = [1, 2, 3, 3, 4, 5, 5]

// Group by value
let grouped = Dictionary(grouping: numArray, by: { $0 })

var uniqueArray = [Int]()

for (key, value) in grouped {
    if value.count == 1 {
        uniqueArray.append(key)
    }
}

print(uniqueArray.sorted()) // [1, 2, 4]

4

solved Using Swift Get array of non repeating numbers from array of numbers