I have a Clojure map that may contain values that are nil and I'm trying to write a function to remove them, without much success (I'm new to this).
E.g.:
(def record {:a 1 :b 2 :c nil}) (merge (for [[k v] record :when (not (nil? v))] {k v}))
This results in a sequence of maps, which isn't what I expected from merge:
({:a 1} {:b 2})
I would like to have:
{:a 1, :b 2}
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
When you want to remove nil elements from a Ruby array, you can use two methods: compact or compact! . They both remove nil elements, but compact! removes them permanently. In this shot, we will be talking about the compact!
your for list comprehension returns a LIST of maps, so you need to APPLY this list to the merge function as optional arguments:
user> (apply merge (for [[k v] record :when (not (nil? v))] {k v})) {:b 2, :a 1}
More concise solution by filtering the map as a sequence and conjoining into a map:
user> (into {} (filter second record)) {:a 1, :b 2}
Dont remove false values:
user> (into {} (remove (comp nil? second) record)) {:a 1, :b false}
Using dissoc to allow persistent data sharing instead of creating a whole new map:
user> (apply dissoc record (for [[k v] record :when (nil? v)] k)) {:a 1, :b 2}
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