Convert nested array in swift to single dimensional array

心不动则不痛 提交于 2020-01-11 14:46:49

问题


I have a structure like [[[ ]]] which I want to convert to [].

E.g. [ [ [ "Hi" ] ] ] into [ "Hi" ]

How can I do this in Swift?


回答1:


joined() returns (a lazy view of) the elements of an collection, concatenated. This can be applied repeatedly for deeper nested collections:

let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]

let flattened = Array(arr.joined().joined())
print(flattened) // ["A", "B", "C", "D", "E", "F"]

The outer Array() constructor builds an array from the sequence. Apart from that, no intermediate arrays are created.

If you just want to iterate over the nested array then the joined sequence is sufficient:

for elem in arr.joined().joined() {
    print(elem)
}



回答2:


Use reduce(_:_:) with your array this way.

let array = [[["One","Two","Three"],["Four","Five"]],[["Six"]]]
let newArray = array.reduce([]) { $0 + $1.reduce([]){ $0 + $1 } }
print(newArray) //["One", "Two", "Three", "Four", "Five", "Six"]



回答3:


This is exactly what flatMap() does:

let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]

// each call reduces the array by one dimension

let flattened = arr.flatMap{$0}.flatMap{$0}

// returns ["A", "B", "C", "D", "E", "F"]



回答4:


you can use join as

let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let newArray = Array(numbers.joined().joined())
print(newArray)//[1,2,3,4,5,6,7,8,9]]


来源:https://stackoverflow.com/questions/42432013/convert-nested-array-in-swift-to-single-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!