filter all elements of multi-dimensional array, conditionally in swift

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.swift
let numbers = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
48 chars
2 lines

Suppose we want to filter all elements greater than or equal to 5 across all sub-arrays, we can write:

main.swift
let filtered = numbers.flatMap { $0.filter { $0 >= 5 } }
57 chars
2 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.swift
print(filtered) // [5, 6, 7, 8, 9]
35 chars
2 lines

You can modify the condition in the closure to match your specific case.

gistlibby LogSnag