简体   繁体   中英

Compare an array with another & then return the index of matched results

Sorry if this is a dumb question but everything I try seems to be wrong. (I am new to Swift).

I have 2 arrays of Strings which I need to compare for matches and then return an array with the index position of those matches.... IE:

let array1 = ["abc", "def", "ghi", "jkl", "xyz", "uhr"]
let array2 = ["ghi", "xyz", "uhr"]

// Search array1 for instances of array2

// Result I want is: [2, 4, 5] 

Is there a simple function I am missing?. Thanks in advance for your help.

var indexArr: [Int] = []

for element in array2 {
    if let elementIndex = array1.firstIndex(of: element) {
       indexArr.append(elementIndex)
    }
}

print(indexArr)
var results: [Int] = []

for i in 0..<array1.count {
   for j in 0..<array2.count {
      if array1[i] == array2[j] {
         results.append(i)
      }
   }
}

print(results)

For an efficient solution you can create an index first. The index maps each element in the first array to its position in the array. Both arrays are traversed only once:

let array1 = ["abc", "def", "ghi", "jkl", "xyz", "uhr"]
let array2 = ["ghi", "xyz", "uhr"]

let index = Dictionary(uniqueKeysWithValues: array1.enumerated().map {
    ($0.element, $0.offset)
})
let result = array2.compactMap { index[$0] }
print(result) // [2, 4, 5]

If the elements in array1 are not known to be unique then the index must be computed slightly differently:

let index = Dictionary(array1.enumerated().map { ($0.element, $0.offset) },
                       uniquingKeysWith: { (first, _) in first })

The second parameter is a closure which controls which value to put into the dictionary in the case of duplicate keys. Here we choose the position of the first occurrence of an element in the array.

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