Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter nil values from Clojure map?

Tags:

What is the best way to filter nil values from a Clojure map {}?

{ :a :x :b nil :c :z }
;;=>  { :a :x, :c :z }
like image 712
Eric Schoonover Avatar asked Feb 18 '12 08:02

Eric Schoonover


3 Answers

I would use:

(into {} (filter (comp some? val) {:a :x, :b nil, :c :z}))  => {:a :x, :c :z} 

Doing the some? check explicitly is important because if you just do (into {} (filter val {...})) then you will erroneously remove values that are boolean false.

like image 92
mikera Avatar answered Oct 27 '22 18:10

mikera


I use following code:

(into {} (filter val {:a 1, :b 2, :c nil}))
;;=> {:a 1, :b 2}

NOTE: this will remove false values as well as nils

like image 29
mishadoff Avatar answered Oct 27 '22 18:10

mishadoff


Probably not the best solution, but here's one that uses list comprehension:

(into {} 
  (for [[k v] {:a 1 :b nil :c :z} :when (not (nil? v))]
    [k v]))
like image 20
skuro Avatar answered Oct 27 '22 20:10

skuro