2

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 ] ]
1
  • Does the first array has only two elements all the time? Commented Mar 30, 2022 at 5:31

2 Answers 2

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]]

Sign up to request clarification or add additional context in comments.

1 Comment

The second approach won't print the desired output if the input is [[1, 2, 3], [4, 5, 6]]
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.