skip to Main Content

I have an array and I want to merge it.

This is the array:

let numbers = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

I need a output like this:

let result = [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]

2

Answers


  1. You can use the zip global function, which, given 2 sequences, returns a sequence of tuples and then obtain an array of tuples by using the proper init.

    var xAxis = [1, 2, 3, 4]
    var yAxis = [2, 3, 4, 5]
    let pointsSequence = zip(xAxis, yAxis)
    let chartPoints = Array(pointsSequence)
    print(chartPoints)
    

    And then you can access the tuples like this :

    let point = chartPoints[0]
    point.0 // This is the 1st element of the tuple
    point.1 // This is the 2nd element of the tuple
    
    Login or Signup to reply.
  2. let numbers = [[1,2,3], [4,5,6]]
    
    let result = zip(numbers[0], numbers[1]).map { [$0.0, $0.1]}
    
    print(result) // -> [[1, 4], [2, 5], [3, 6]]
    

    If the array has more elements the following would work.

    let numbers = [[1,2,3], [4,5,6], [7,8,9]]
    
    var result : [[Int]] = []
    
    for n in 0...numbers.first!.count-1{
        result.append(numbers.compactMap { $0[n] })
    }
    
    print(result) // -> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search