Ad

Swift 3 - Compare Two Unequal Length Arrays And Append Placeholder Values In It To Make Them Equal

- 1 answer

My first array is

arr1 = [1, 2, 3, 4 , 5]

My second array is

arr2 = [2, 3, 4]

I want to compare arr1 against arr2 and output a third array with the output

arr3 = ["No match", 2, 3, 4, "No match"]

So that I have added a placeholder value at indices where arr1 and arr2 dont match. Arr1 and arr2 will not always be sorted.

How do i go about this in Swift 3? Can't come up with a loop that will work :/

Ad

Answer

a simple solution will be

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

var arr3 = [String]()
for value in arr1{

    if arr2.contains(value){
        arr3.append("\(value)")
    } else {
        arr3.append("No Match")
    }
}

one line solution would be

let results = arr1.map {arr2.contains($0) ? "\($0)" : "No Match"}
Ad
source: stackoverflow.com
Ad