{

Multiple ways to flatten an array in the swift example


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)
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.