Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nil values from a map?

Tags:

clojure

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} 
like image 356
edoloughlin Avatar asked Oct 14 '10 21:10

edoloughlin


People also ask

How do you remove nil from an array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

How do you get rid of nil in Ruby?

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!


1 Answers

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}   
like image 123
Jürgen Hötzel Avatar answered Sep 28 '22 06:09

Jürgen Hötzel