How to flatten a 2D array into a sorted one-dimensional array in Swift

1 Answer

0 votes
import Foundation

// Function that flattens a 2D array and returns a sorted 1D array
func flattenAndSort(_ array2d: [[Int]]) -> [Int] {

    // 1. Flatten the 2D array into a single array
    //    flatMap merges each row into one continuous sequence
    let flattened = array2d.flatMap { $0 }

    // 2. Sort the flattened array
    return flattened.sorted()
}

let array2d = [
    [4, 5, 3],
    [30, 20],
    [10],
    [1, 2, 6, 7, 8]
]

let arr = flattenAndSort(array2d)

// Print result as comma‑separated values
print(arr.map(String.init).joined(separator: ", "))


/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered 2 hours ago by avibootz

Related questions

...