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)]
Use zip
and map
:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
let tuples = zip(xaxis, yaxis).map { ($0, $1) }
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)
Try this:
let arrayMerged = zip(xaxis, yaxis).map { ($0, $1) }
or this:
let arrayMerged = Array(zip(xaxis, yaxis))
let tuples = xaxis.enumerated().map { (index, value) in (value, yaxis[index]) }
Assuming yaxis
's count always matches to xaxis
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With