我有三个数组,如[“a”,“d”,“c”] [“x,p,z”] [“o,n,q”]。我想将数组合并到数组到单个数组,如[“a”,“c”,“d”,“n”,“o”,“p”,“q”,“x”,“z”]并且必须对它进行排序。
我试过这样的方式
var arr1 = ["a","x","d"]
let str2 = "byq".characters.map { String($0) } // Manually i did string to array conversion
var arr2 = Array(str2)
let str3 = "cmo".characters.map { String($0) } // Manually i did string to array conversion
var arr3 = Array(str3)
var formattedArr2: [String] = [(arr2.map{String($0)}).joined(separator: ",")]
func combineArrays<T>(arrays:[[T]]) -> [T] {
let maxCount = arrays.reduce(0) {max($0, $1.count)}
var result = [T]()
for i in 0..<maxCount {
for array in arrays {
if i < array.count {
result.append(array[i])
}
}
}
return result
}
print(combineArrays(arrays: [arr1,arr2,arr3]).sorted())
我的答案是["a","c","d","n","o","p","q","x","z"]
。但我做错了。请任何人都可以提出将数组合并到单个数组中的数组的想法
如何合并这个数组并从[[“a”,“d”,“c”],[“x,p,z”],[“o,n,q”]]拆分成单个字符?
答案 0 :(得分:4)
你在找这样的东西吗?
let sortedArray = [arr1, arr2, arr3].flatMap { $0 }.sorted()
编辑:或许这个?
let sortedArray = ([["a","d","c"],["x,p,z"],["o,n,q"]].flatMap { $0 } as [String]).flatMap { $0.split(separator: ",")}.sorted()
编辑(结果相同,但海报首选):
let sortedArray = ([["a","d","c"],["x,p,z"],["o,n,q"]].flatMap { $0 } as [String]).flatMap { $0.components(separatedBy: ",") }.sorted()