Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

Get items with the same position from multidimensional array in Swift 5

I can't find the best way to do this.

I have an array with 3 arrays in there(this never change)

var ancho = [String]()
var largo = [String]()
var cantidad = [String]()
var arrayDeCortes = [ancho,largo,cantidad]

arrayDeCortes = [[a,b,c,d,..],[e,f,g,h,..],[i,j,k,l,..]]

I need to get this:

[a,e,i]
[b,f,j]
[c,g,k]
[d,h,l]

My problem is that I don't know how many items there is in each array(ancho,largo,cantidad) and how access to all of them.

I hope you understand me

question from:https://stackoverflow.com/questions/65910398/get-items-with-the-same-position-from-multidimensional-array-in-swift-5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use reduce(into:_:) function of Array like this:

let arrayDeCortes = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

let arrays = arrayDeCortes.reduce(into: [[String]]()) { (result, array) in
    array.enumerated().forEach {
        if $0.offset < result.count {
            result[$0.offset].append($0.element)
        } else {
            result.append([$0.element])
        }
    }
}

print(arrays)
// [["a", "e", "i"], ["b", "f", "j"], ["c", "g", "k"], ["d", "h", "l"]]

Edit: As @Alexander mentioned in the comments, there is a simpler way of achieving this by using zip(_:_:) function twice.

The following will return an array of tuples:

var widths = ["a","b","c","d"]
var heights = ["e","f","g","h"]
var quantities = ["i","j","k","l"]

let result = zip(widths, zip(heights, quantities)).map { width, pair in
    (width, pair.0, pair.1)
}

print(result)
// [("a", "e", "i"), ("b", "f", "j"), ("c", "g", "k"), ("d", "h", "l")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...