1

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

Fer Romero
  • 15
  • 3
  • you are trying to transpose the array. Look at this https://stackoverflow.com/questions/32920002/how-to-transpose-an-array-of-strings or this https://stackoverflow.com/questions/45412684/how-to-transpose-a-matrix-of-unequal-array-length-in-swift-3 – timbre timbre Jan 26 '21 at 23:19
  • thanks so much! I was looking for it wrong.@KirilS. – Fer Romero Jan 27 '21 at 00:46
  • From google translate, I gather that these arrays are called `width`/`length`/`quantity`. It looks like you have parallel arrays. Where did you get these from? It's better that you make a single array of `Cut` structs, each with a width, length and quantity. – Alexander Jan 27 '21 at 15:13
  • Yes, you’re right. This is my first project Im trying to make an Cut Optimizer, that means I need the user to load those parameters and then render them on a plane. I have a UITableView and a cell with 3 textfields(width/length/quantity), I also have a “add cell”button. When the button is pressed my textfields are duplicated, that’s what I end up with a multidimensional array. Maybe I’m doing something wrong in my table view. Thanks!! – Fer Romero Jan 29 '21 at 04:32

1 Answers1

0

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")]
gcharita
  • 7,729
  • 3
  • 20
  • 37