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.
Multiple ways to flatten an array in swift with code examples
reduce
functionjoined
functionflatMap
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]
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)
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)
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)
🧮 Tags
Recent posts
Learn Golang Tutorials - Rune Types Explained with examples How to display images in Hugo with examples | Hugo Image shortcode Nodejs package.json resolutions How to find Operating System username in NodeJS? How to convert Double to Integer or Integer to double in Dart| Flutter By ExampleRelated posts