简体   繁体   中英

Swift 3 - Array mapping. Add placeholder values in array based on relationship

My first array is:

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

My second array is:

arr2 = [2, 3, 4]

My third array is:

arr3 = ["2a", "3a", "4a"]

arr2 and arr3 are related by index values, ie, arr2[0] relates to arr3[0], same for [1] and [2].

I have been able to compare arr2 against arr1 and add placeholder values so my placeholder array for them is

arr1to2 = ["No match", 2, 3, 4, "No Match"]

Now I need to compare arr3 against arr2 to arr1 (alternatively arr1to2), so my output should be

array_final = ["No match", 2a, 3a, 4a, "No match"]

I need to have the relationship maintained between index values of array_final and arr1to2 as well. [1] relates [1], [2] to [2], [3] to [3].

You can do it this way:

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [2, 3, 4]
let arr3 = ["2a", "3a", "4a"]

// first lets join arr2 and arr3 to a dictionary
var dict: [Int: String] = [:]
zip(arr2, arr3).forEach({ (pair) in
    dict[pair.0] = pair.1
})

// and then just map each value in arr1 according to the dictionary, or provide a "No match" default
let result = arr1.map { (value) -> String in
    return dict[value] ?? "No match"
}

print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM