简体   繁体   中英

How to get the items of an array based on the indexes stored in another array

I have two arrays:

let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]

a contains all the items and b contains the indexes of the ones I'm interested in.
So I would like to create a function to extract the items at the indexes specified in array b .

I can do tis with for loops:

for i in 0...a.count-1{
    if i == b[i]{
    print(a[i])
  }
}

To make it clear, the desired output would be:

banana orange kiwi

The problem is that with big numbers the for loop would be too slow.
I would like to know if there exists something with a lower complexity.

You can simply map the indices and return the associated elements:


let aa = ["apple","banana","orange","pomelo","kiwi","melon"]
let bb = [1, 2, 4]

let elements = bb.map { aa[$0] }
print(elements)    // ["banana", "orange", "kiwi"]

Or extending RandomAccessCollection protocol:


extension RandomAccessCollection {
    func elements(at indices: [Index]) -> [Element] { indices.map { self[$0] } }
}

let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]

let elements = a.elements(at: b)    // ["banana", "orange", "kiwi"]

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