What is the best way to filter nil
values from a Clojure map {}
?
{ :a :x :b nil :c :z }
;;=> { :a :x, :c :z }
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.
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
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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With