Filtering Collections in Swift, Kotlin and JavaScript
Extracting members of a collection that match some filtering predicate is a common pattern in programming. Traditionally we would iterate over all members (e.g. with a for or foreach loop), and save each member matching some condition. Most programming languages now provide some single step filter
function to eliminate the need for manual iteration.
For the simple case of filtering, most languages take a collection and some predicate as input, and returns a subset of the original collection as output.
Swift
struct Contact {
let name: String
let email: String
}
let allContacts = [
Contact(name: "John Doe", email: "john@doe.com"),
Contact(name: "Mary Johansson", email: "mary@aol.com"),
Contact(name: "Jack Splat", email: "jack@splat.com")
]
let filtered = allContacts.filter { $0.name.contains("Joh") }
print(allContacts)
/*
[Contact(name: "John Doe", email: "john@doe.com"), Contact(name: "Mary Johansson", email: "mary@aol.com")]
*/
Kotlin
data class Contact(val name: String, val email: String)
fun main() {
val allContacts = listOf(
Contact("John Doe", "john@doe.com"),
Contact("Mary Johansson", "mary@aol.com"),
Contact("Jack Splat", "jack@splat.com")
)
val filtered = allContacts.filter { it.name.contains("Joh")}
print(filtered)
}
/*
[Contact(name=John Doe, email=john@doe.com), Contact(name=Mary Johansson, email=mary@aol.com)]
*/
JavaScript
const allContacts = [
{ name: "John Doe", email: "john@doe.com" },
{ name: "Mary Johansson", email: "mary@aol.com" },
{ name: "Jack Splat", email: "jack@splat.com" }
]
const filtered = allContacts.filter(contact => contact.name.includes("Joh"))
/*
[
{
"name": "John Doe",
"email": "john@doe.com"
},
{
"name": "Mary Johansson",
"email": "mary@aol.com"
}
]
*/