Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple keys from a map?

Tags:

clojure

I have a function that removes a key from a map:

(defn remove-key [key map]   (into {}         (remove (fn [[k v]] (#{key} k))                 map)))  (remove-key :foo {:foo 1 :bar 2 :baz 3}) 

How do i apply this function using multiple keys?

(remove-keys [:foo :bar] {:foo 1 :bar 2 :baz 3}) 

I have an implementation using loop...recur. Is there a more idiomatic way of doing this in Clojure?

(defn remove-keys [keys map]   (loop [keys keys          map map]     (if (empty? keys)       map       (recur (rest keys) (remove-key (first keys) map))))) 
like image 424
Sathish Avatar asked Mar 15 '12 10:03

Sathish


People also ask

How do I get rid of multiple keys on a map?

Assuming your set contains the strings you want to remove, you can use the keySet method and map. keySet(). removeAll(keySet); . keySet returns a Set view of the keys contained in this map.

How do I delete a map key?

To delete a key from a map, we can use Go's built-in delete function. It should be noted that when we delete a key from a map, its value will also be deleted as the key-value pair is like a single entity when it comes to maps in Go.

How do I remove all elements from a map?

HashMap. clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Parameters: The method does not accept any parameters. Return Value: The method does not return any value.


1 Answers

Your remove-key function is covered by the standard library function dissoc. dissoc will remove more than one key at a time, but it wants the keys to be given directly in the argument list rather than in a list. So you can use apply to "flatten" it out.

(apply dissoc {:foo 1, :bar 2, :baz 3} [:foo :bar]) ==> {:baz 3} 
like image 95
deong Avatar answered Oct 05 '22 12:10

deong