Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Specter: how to find map keys that have specific value?

Eg in a map:

{"test-1" 23,
 "test-2" 456,
 "test-3" 23}

How to find keys that have value 23?

like image 983
sumek Avatar asked Dec 24 '22 14:12

sumek


2 Answers

I think you don't need specter to do that, just filter by value. I.e:

(->> {:key-1 10
      :key-2 20
      :key-3 10}
      (filter (fn [[k v]] (= v 10)))
      (map first))
==>  [:key-1 :key-3]

A solution with Specter is:

(keys (specter/setval [specter/MAP-VALS #(not= 10 %)]
                       specter/NONE
                       {:key-1 10
                        :key-2 20
                        :key-3 10}))
like image 148
Minh Tuan Nguyen Avatar answered Feb 06 '23 19:02

Minh Tuan Nguyen


If you want to find something using Specter, it is better to use specter/select.

(use 'com.rpl.specter)    

(select [ALL #(= (second %) 23) FIRST]
  {"test-1" 23,
   "test-2" 456,
   "test-3" 23})
like image 39
alex.dorokhov Avatar answered Feb 06 '23 18:02

alex.dorokhov