如何按字母顺序对多维字符数组进行排序Swift

时间:2017-09-28 00:50:31

标签: swift sorting multidimensional-array

我正在尝试对包含随机字符的[[Character]]数组进行排序,以使其全部按字母顺序排列。现在的输出:

["H", "P", "C"]
["F", "K", "V"]
["J", "Y", "B"]

我需要它像这样

["A", "B", "C"]
["D", "E", "F"]
["G", "H", "I"]

任何想法?

3 个答案:

答案 0 :(得分:0)

请检查:

let input = [["H", "P", "C"], ["F", "K", "V"], ["J", "Y", "B"], ["A", "L"]]
var sortedArray = input.flatMap({ $0 }).sorted()

var finalArray:[[String]]=[]
var subArray:[String]=[]
for i in 0..<sortedArray.count {
    subArray.append(sortedArray[i])
    if subArray.count == 3 || i == sortedArray.count-1 {
        finalArray.append(subArray)
        subArray = []
    }
}

print(finalArray) 
// Output : [["A", "B", "C"], ["F", "H", "J"], ["K", "L", "P"], ["V", "Y"]]

答案 1 :(得分:0)

func flattenArray(nestedArray: [[Character]]) -> [[Character]]{

var myFlattendArray = [Character]()
var sortedArray = [[Character]]()

for element in nestedArray{
    if element is [Character]{
        for char in element{
            myFlattendArray.append(char)
        }
    }
}
myFlattendArray = myFlattendArray.sorted(by: {$0 < $1})
var arrayForArray = [Character]()
for i in 0..<myFlattendArray.count{
   if((i % nestedArray.count == 0 && i != 0)){
        sortedArray.append(arrayForArray)
        arrayForArray.removeAll()
   }else if i == myFlattendArray.count - 1{
        arrayForArray.append(myFlattendArray[i])
        sortedArray.append(arrayForArray)
        arrayForArray.removeAll()
   }
   arrayForArray.append(myFlattendArray[i])

}
   return sortedArray
}

答案 2 :(得分:0)

您可以使用flatMap展平您的数组,对其进行排序,然后您可以使用此answer中的此扩展进行分组,如下所示:

extension Array {
    func group(of n: IndexDistance) -> Array<Array> {
        return stride(from: 0, to: count, by: n)
            .map { Array(self[$0..<Swift.min($0+n, count)]) }
    }
}

let arr = [["H", "P", "C"],
           ["F", "K", "V"],
           ["J", "Y", "B"]]

let sorted = arr.flatMap{$0}.sorted().group(of: 3)
sorted  // [["B", "C", "F"], ["H", "J", "K"], ["P", "V", "Y"]]