Multiple ways to flatten an array in the swift example

Multiple ways to flatten an array in Swift with code examples

  • Array reduce function
  • Array joined function
  • Array flatMap function The array contains a sequence of elements, and it contains different dimensions.

Flattening is a process of converting or reducing a multiple given dimensions array into a single dimension.

Flatten an array of the array is converted to an array. For example, Given an array of arrays as given below

[[1,2],[3,4],[5,6],[7,8,9,10]]

And output is

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array flatten swift with examples

There are multiple ways to flatten an array in Swift.

  • Using the Array reduce method

    Array reduce method takes a sequence type such as array and applies the operation such as combine and return reduced value.

Here is an example

import Foundation
var numbers = [[1,2],[3,4],[5,6],[7,8,9,10]]
let result = numbers.reduce([], +)
print(result)
  • Array joined the function

The joined method in the array concatenates the elements and passes this result into the Array object.

import Foundation
var numbers = [[1,2],[3,4],[5,6],[7,8,9,10]]
let result = Array(numbers.joined())

print(result)
  • Array flatMap function

The flatMap method in an array concatenates the elements and flattens an array.

import Foundation
var numbers = [[1,2],[3,4],[5,6],[7,8,9,10]]
let result = numbers.flatMap { $0 }
print(result)