Swift Language Swift Advance functions Flatten multidimensional array


Example

To flatten multidimensional array into single dimension, flatMap advance functions is used. Other use case is to neglect nil value from array & mapping values. Let's check with example:-

Suppose We have an multidimensional array of cities & we want to sorted city name list in ascending order. In that case we can use flatMap function like:-

let arrStateName = [["Alaska", "Iowa", "Missouri", "New Mexico"], ["New York", "Texas", "Washington", "Maryland"], ["New Jersey", "Virginia", "Florida", "Colorado"]]

Preparing a single dimensional list from multidimensional array,

let arrFlatStateList = arrStateName.flatMap({ $0 }) // ["Alaska", "Iowa", "Missouri", "New Mexico", "New York", "Texas", "Washington", "Maryland", "New Jersey", "Virginia", "Florida", "Colorado"]

For sorting array values, we can use chaining operation or sort flatten array. Here below example showing chaining operation,

// Swift 2.3 syntax 
let arrSortedStateList = arrStateName.flatMap({ $0 }).sort(<) // ["Alaska",     "Colorado", "Florida", "Iowa", "Maryland", "Missouri", "New Jersey", "New Mexico", "New York", "Texas", "Virginia", "Washington"]

// Swift 3 syntax
let arrSortedStateList = arrStateName.flatMap({ $0 }).sorted(by: <) // ["Alaska", "Colorado", "Florida", "Iowa", "Maryland", "Missouri", "New Jersey", "New Mexico", "New York", "Texas", "Virginia", "Washington"]