Flatten an Array of Arrays in Swift


In Swift, you can use higher-order functions to flatten an array of arrays. You can use a combination of joined(), reduce(), and flatMap() functions. Sometimes, you are required to merge multiple arrays into a single array. In Swift, you can easily do that using high-order functions. In this article, we will see some examples of different use cases.

Example 1: Using the flatMap() Function

To flatten an array of arrays in Swift, you can use the joined() method along with the flatMap() function. Here's an example.

import Foundation
let arrayOfArrays = [[1, 2], [3, 4], [5, 6, 7]]
let flattenedArray = arrayOfArrays.flatMap { $0 }
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [[1, 2], [3, 4], [5, 6, 7]]
Flattened Array: [1, 2, 3, 4, 5, 6, 7]

In this example, flatMap() is used to map each sub-array in arrayOfArrays to its elements, and then joined() is used to concatenate the resulting arrays together into a single flat array.

Example 2: Using the reduce() Function

Alternatively, you can use the reduce() method to flatten the array. Here's an example.

import Foundation
let arrayOfArrays = [[1, 2], [3, 4], [5, 6, 7]]
let flattenedArray = arrayOfArrays.reduce([], +)
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [[1, 2], [3, 4], [5, 6, 7]]
Flattened Array: [1, 2, 3, 4, 5, 6, 7]

In this example, reduce() is used to combine all the sub-arrays into a single array by starting with an empty array and using the + operator to append each sub-array.

Example 3: Flattening an Array of Arrays with Optionals

Alternatively, you can use the flatMap() method to flatten the optional arrays. Here's an example.

import Foundation
let arrayOfArrays: [[Int?]] = [[1, nil], [3, 4, 5], [nil, 7]]
let flattenedArray = arrayOfArrays.flatMap { $0 }
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [[Optional(1), nil], [Optional(3), Optional(4), Optional(5)], [nil, Optional(7)]]
Flattened Array: [Optional(1), nil, Optional(3), Optional(4), Optional(5), nil, Optional(7)]

In this example, the arrayOfArrays is an array of arrays containing Int? optionals. The resulting flattenedArray contains all the elements of the sub-arrays, including nil values.

Example 4: Flattening an Array of Arrays with Duplicates

Alternatively, you can use the Set with flatMap() method to flatten the array. Here's an example.

import Foundation
let arrayOfArrays = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
let flattenedArray = Set(arrayOfArrays.flatMap { $0 })
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Flattened Array: [5, 1, 4, 3, 2]

In this example, the arrayOfArrays is an array of arrays containing some duplicate elements. The resulting flattenedArray is a Set of all the unique elements in the sub-arrays, in no particular order.

Example 5: Flattening an Array of Arrays of Strings for use in a search Bar

Alternatively, you can use the flatMap() method to flatten the array of strings. Here's an example.

import Foundation
let arrayOfArrays = [["apple", "orange"], ["banana", "grape"], ["pear", "pineapple"]]
let flattenedArray = Set(arrayOfArrays.flatMap { $0 })
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [["apple", "orange"], ["banana", "grape"], ["pear", "pineapple"]]
Flattened Array: ["pineapple", "grape", "apple", "orange", "pear", "banana"]

In this example, the arrayOfArrays is an array of arrays of strings representing different types of fruits. The resulting flattenedArray can be used as a data source for a search bar, allowing the user to search for any fruit by name.

Example 6: Flatten an Array of Arrays using a For Loop in Swift

Using a for loop can be useful in situations where you need more control over the iteration process. Here's an example.

import Foundation
let arrayOfArrays = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
var flattenedArray: [Int] = []
for subArray in arrayOfArrays {
   for element in subArray {
      flattenedArray.append(element)
   }
}
print("Input array: \(arrayOfArrays)")
print("Flattened Array: \(flattenedArray)")

Output

Input array: [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Flattened Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, we start with an arrayOfArrays of Int values, representing different subsets of data. We then declare an empty flattenedArray of type [Int] to hold the flattened values.

We then use a nested for loop to iterate over each sub-array in arrayOfArrays, and for each sub-array, we iterate over each element in the sub-array and append it to the flattenedArray.

Conclusion

In Swift, flattening an array of arrays means converting a nested array structure into a single flat array containing all the elements from the sub-arrays, in the order they appear.

There are different ways to flatten an array of arrays in Swift, including using the flatMap method, which is a concise and efficient approach, and using a for loop, which provides more control over the iteration process.

Flattening an array of arrays can be useful in many practical scenarios. For example, preparing data for use in a search bar, graph, or table view.

Updated on: 04-May-2023

714 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements