filter

added
1.0

ns
clojure.core

type
function

(filter pred) (filter pred coll)

Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects.
Returns a transducer when no collection is provided.

                (filter even? (range 10))
;;=> (0 2 4 6 8)

(filter (fn [x]
  (= (count x) 1))
  ["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ("a" "b" "n" "f" "q")

(filter #(= (count %) 1)
  ["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ("a" "b" "n" "f" "q")

; When coll is a map, pred is called with key/value pairs.
(filter #(> (second %) 100)
       {:a 1
        :b 2
        :c 101
        :d 102
        :e -1})
;;=> ([:c 101] [:d 102])

(into {} *1)
;;=> {:c 101, :d 102}

            
                ;; Used without a collection, filter will create a transducer:
(def xf (filter odd?))

;; We can now apply this transducer to a sequence:
(transduce xf conj (range 10))
;; => [1 3 5 7 9]

            
                ;;When filtering a map, the predicate takes a _list_ of length 2
(filter (fn [[k v]] (even? k))
    {1 "a", 2 "b", 3 "c", 4 "d"}
)
;;output:: ([2 "b"] [4 "d"])

;;A function of arity two will cause an error
(comment will fail!) 
(filter (fn [k v] (even? k))
    {1 "a", 2 "b", 3 "c", 4 "d"}
)
;;output:: clojure.lang.ArityException: Wrong number of args (1) passed to: ...
            
                ; remove empty vectors from the root vector
(def vector-of-vectors [[1 2 3] [] [1] []])

(def populated-vector? 
  (fn 
    [item] 
    (not= item [])))

(filter populated-vector? vector-of-vectors)

; => ([1 2 3] [1])
            
                ;;filter a map on its values
(filter (comp #{2 3} last) {:x 1 :y 2 :z 3})
;;=> ([:y 2] [:z 3])
            
                ;;filter a map on its values
(filter (comp #{2 3} last) {:x 1 :y 2 :z 3})
;;=> ([:y 2] [:z 3])

;;extract keys for certain values
(map first (filter (comp #{2 3} last) {:x 1 :y 2 :z 3}))
=> (:y :z)
            
                ;; You can use set as a filter predicate. In this case it is sets intersection
(filter #{0 1 2 3} #{2 3 4 5})
=> (3 2)
            
                ;; That's how to get everything from a seq that is not nil;
(filter some? '(1 nil [] :a nil))
=> (1 [] :a)