Convert nested array in swift to single dimensional array

后端 未结 4 1719
谎友^
谎友^ 2021-01-29 12:59

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

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

How

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 13:12

    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"]
    

提交回复
热议问题