To filter all elements of a multi-dimensional array conditionally in Swift, you can use the filter
method.
Consider the following multi-dimensional array of integers:
main.swift48 chars2 lines
Suppose we want to filter all elements greater than or equal to 5 across all sub-arrays, we can write:
main.swift57 chars2 lines
This code will first flatten the multi-dimensional array into a one-dimensional array using flatMap
, and then filter elements in one pass using filter
.
The result will be a new array containing only the values that satisfy the condition:
main.swift35 chars2 lines
You can modify the condition in the closure to match your specific case.
gistlibby LogSnag