0

So with two arrays:

  1. [1, 2, 3, 4, 5]
  2. [100, 200, 400, 800, 1600]

How would I return:

[1, 100, 2, 200, 3, 400, 4, 800]

I know with zip(firstArray, secondArray) I can return [(1,100), (2,200)] etc...

But I'm not looking to work with tuples in this occasion. Any ideas?

Sergio Bost
  • 2,591
  • 2
  • 11
  • 29

2 Answers2

2

You can just map them to arrays & flatMap the result:

let a = [1, 2, 3, 4, 5]
let b = [100, 200, 400, 800, 1600]

let c = zip(a, b).map { [$0.0, $0.1] }.flatMap { $0 }

print(c) // Gives [1, 100, 2, 200, 3, 400, 4, 800, 5, 1600]

or as pointed out in the comments by @Sweeper with a single flatMap:

let c = zip(a, b).flatMap { [$0.0, $0.1] }
Alladinian
  • 34,483
  • 6
  • 89
  • 91
1

Without using Alladinian intermediate map, since it's useless:

let a = [1, 2, 3, 4, 5]
let b = [100, 200, 400, 800, 1600]

let c = zip(a, b).flatMap { [$0.0, $0.1] }
Alastar
  • 1,284
  • 1
  • 8
  • 14