This page describes an operation in the collection pipeline pattern. For more context read:
- Collection Pipeline Article: An article explaining the collection pipeline pattern
- Operation Catalog: The list of selected operations that I have these pages for.
filter
Runs a boolean function on each element and only puts those that pass into the output.
You can use this function to keep only the items of the input you want to work with. For example:
[1,2,3,4].select {|i| i.even?} # => [2, 4]
(filter even? [1 2 3 4]) ;; => (2 4)
Many languages use the term “select” for this operation. An advantage with the “select” wording is that “reject” makes a natural complement.
ruby…[1,2,3,4].select {|i| i.even?} # => [2, 4] [1,2,3,4].reject {|i| i.even?} # => [1, 3]
“remove” is sometimes used for “reject” where languages use “filter”.
The biggest downside with using “select” as the name is that some libraries (such as dot net's Linq) use “select” as the name for map (based on the usage from sql where “select” projects a subset of fields, which is a specialized form of map).
As with many operations, there are wrinkles involved in filtering hashes. Destructuring a single argument into a key and value works well for languages, like Clojure, that support it.
clojure…(filter (fn [[k,v]] (> v 2)) {:BR 5, :IT 4, :ES 1} ) ;; => ([:IT 4] [:BR 5])
OO languages need to have a filter operation defined on the hash class - ruby does this with select.
ruby…{BR: 5, IT: 4, ES: 1}.select{|k,v| v > 2} # => {:BR=>5, :IT=>4}