Skip to content
DeveloperMemos

Flattening an Array of Arrays in Swift

Swift, Arrays, Data Structures1 min read

In Swift, handling arrays efficiently is crucial for performance and convenience. Sometimes, you might find yourself working with an array of arrays (a 2D array) and need to flatten it into a single array. This article will guide you through the process of flattening an array of arrays in Swift.

Understanding the Problem

Suppose you have a 2D array, where each element is an array itself. The goal is to combine these nested arrays into a single array.

Example of a 2D array:

1let arrayOfArrays = [[1, 2, 3], [4, 5], [6]]

Method 1: Using flatMap

Swift provides a convenient method called flatMap which can be used to flatten an array of arrays.

1let flattenedArray = arrayOfArrays.flatMap { $0 }

The flatMap method iterates over each element in the arrayOfArrays, and $0 refers to each nested array. The result is a single, flattened array.

Method 2: Using reduce

Another method to achieve this is using the reduce function.

1let flattenedArray = arrayOfArrays.reduce([], +)

This method starts with an empty array ([]) and then concatenates each element of arrayOfArrays to it.

Handling Complex Nested Arrays

If you have a more complex nested array structure, you may need to implement a custom flattening function. Here's an example of a recursive function for deep flattening:

1func deepFlatten(_ array: [Any]) -> [Int] {
2 var flattened = [Int]()
3
4 for element in array {
5 if let number = element as? Int {
6 flattened.append(number)
7 } else if let nestedArray = element as? [Any] {
8 flattened.append(contentsOf: deepFlatten(nestedArray))
9 }
10 }
11
12 return flattened
13}
14
15let complexArray: [Any] = [1, [2, [3, 4], 5], 6]
16let deeplyFlattened = deepFlatten(complexArray)

In the end, just remember to choose the method that best fits your specific scenario and performance needs!