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

1 Answer

0 votes
import Foundation

// Function that flattens a 2D array, sorts it, removes duplicates,
// and returns a new sorted array with unique values
func flattenSortUnique(_ array2d: [[Int]]) -> [Int] {

    // 1. Flatten the 2D array into a 1D array
    let flat = array2d.flatMap { $0 }

    // 2. Sort the flattened array
    let sorted = flat.sorted()

    // 3. Remove duplicates using Set, then sort again to preserve order
    let unique = Array(Set(sorted)).sorted()

    return unique
}

let array2d: [[Int]] = [
    [4, 3, 3, 2, 4],
    [30, 10, 10],
    [10, 30],
    [1, 1, 6, 7, 7, 7, 8]
]

let arr = flattenSortUnique(array2d)

// Print results
for n in arr {
    print("\(n)\t", terminator: "")
}



/*
run

1	2	3	4	6	7	8	10	30	

*/

 



answered 2 hours ago by avibootz

Related questions

...