To conditionally flatten a nested array, you can use flatMap(_:)
method in Swift:
main.swift149 chars4 lines
In the above code, we are using flatMap(_:)
to flatten the nested array, and using a condition to skip empty arrays. By returning nil
from the closure for empty arrays, we are effectively removing them from the flattened array.
The output of the above code will be:
main.swift28 chars2 lines
This technique can be used with any condition for filtering elements from the nested arrays.
gistlibby LogSnag