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

 1struct Contact {
 2    let name: String
 3    let email: String
 4}
 5
 6let allContacts = [
 7    Contact(name: "John Doe", email: "john@doe.com"),
 8    Contact(name: "Mary Johansson", email: "mary@aol.com"),
 9    Contact(name: "Jack Splat", email: "jack@splat.com")
10]
11
12let filtered = allContacts.filter { $0.name.contains("Joh") }
13
14print(allContacts)
15
16/*
17[Contact(name: "John Doe", email: "john@doe.com"), Contact(name: "Mary Johansson", email: "mary@aol.com")]
18*/

Kotlin

 1data class Contact(val name: String, val email: String)
 2
 3fun main() {
 4	val allContacts = listOf(
 5        Contact("John Doe", "john@doe.com"),
 6        Contact("Mary Johansson", "mary@aol.com"),
 7        Contact("Jack Splat", "jack@splat.com")
 8    )
 9    
10    val filtered = allContacts.filter { it.name.contains("Joh")}
11    
12    print(filtered)
13}
14
15/*
16[Contact(name=John Doe, email=john@doe.com), Contact(name=Mary Johansson, email=mary@aol.com)]
17*/

JavaScript

 1const allContacts = [
 2    { name: "John Doe", email: "john@doe.com" },
 3    { name: "Mary Johansson", email: "mary@aol.com" },
 4    { name: "Jack Splat", email: "jack@splat.com" }
 5]
 6
 7const filtered = allContacts.filter(contact => contact.name.includes("Joh"))
 8
 9/*
10[
11  {
12    "name": "John Doe",
13    "email": "john@doe.com"
14  },
15  {
16    "name": "Mary Johansson",
17    "email": "mary@aol.com"
18  }
19]
20*/