[SOLVED] Swift – I need to find elements from array 2 that are not in array 1

Issue

i tried something like this, but it doesn’t fit

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [7, 2, 2, 4, 5]


for (index, item) in arr2.enumerated() where arr1.contains(item {
    print(arr2[index])
}

Solution

You can get the collection elements frequency and just filter the elements that doesnt match from second collection

let array1 = [8, 8, 7, 2, 1, 7, 9]
let array2 = [14, 8, 2, 7, 7]
let frequency1 = array1.reduce(into: [:]) { $0[$1, default: 0] += 1 }
let frequency2 = array2.reduce(into: [:]) { $0[$1, default: 0] += 1 }
var set: Set<Int> = []
let elements = array2.filter {
    frequency1[$0] != frequency2[$0] ? set.insert($0).inserted : false
}
elements  //  [14, 8]

Answered By – Leo Dabus

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *