Reputation: 981
I have the following two arrays:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
I would like to merge them into an array that looks like this:
[ ("monday", 1), ("tuesday", 2), ("wednesday", 3), ("thursday", 4), ("friday", 5)]
Upvotes: 10
Views: 4871
Reputation: 437442
Use zip
and map
:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
let tuples = Array(zip(xaxis, yaxis)) // or `zip(xaxis, yaxis).map { ($0, $1) }`
I know you asked about a tuple, but you can also consider a custom object, e.g.:
struct Day {
let name: String
let value: Int
}
let names = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let values = [1, 2, 3, 4, 5]
let days = zip(names, values).map(Day.init)
Upvotes: 24
Reputation: 7585
Try this:
let arrayMerged = zip(xaxis, yaxis).map { ($0, $1) }
or this:
let arrayMerged = Array(zip(xaxis, yaxis))
Upvotes: 3
Reputation: 3606
Try this:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
var newArr = [(String, Int)]()
for i in 0..<xaxis.count {
newArr.append((xaxis[i], yaxis[i]))
}
print(newArr)
Upvotes: 2
Reputation: 1504
let tuples = xaxis.enumerated().map { (index, value) in (value, yaxis[index]) }
Assuming yaxis
's count always matches to xaxis
.
Upvotes: 1