Clojure: creating a map with switched keys and values from another map -


i trying create kind of reverted index input map. input map got is:

{"id-1" {"values" ["a" "b" "c"]}, "id-2" {"values" ["a" "b" "c"]}} 

then want have other map result:

{"a" ["id-1" "id-2"], "b" ["id-1" "id-2"], "c" ["id-1" "id-2"]} 

however, think mind did go crazy, , think painted myself corner without being able of thinking out of box. here got far, , looks stinks:

(->> {"id-1" {"values" ["a" "b" "c"]} "id-2" {"values" ["a" "b" "c"]}}        (map #(->> (get (second %) "values")               (map (fn [x y] (hash-map y x)) (into [] (repeat (count (get (second %) "values")) (first %))))               (apply merge-with concat)))        (apply merge-with concat)) 

basically, use first map used "iterate" on input values. use second map create series of individual maps looks that:

({"a" "id-2"} {"b" "id-2"} {"c" "id-2"} {"a" "id-1"} {"b" "id-1"} {"c" "id-1"}) 

to map, create intermediary array using into [] (repeat ..) feed map along array of values.

then merge them expected value.

two issues here:

  1. this seems more complex have intuition is
  2. the current end result not yet perfect since getting this:

    {"a" (\i \d - \1 \i \d - \2), "b" (\i \d - \1 \i \d - \2), "c" (\i \d - \1 \i \d - \2)}

given input:

(def input {"id-1" {"values" ["a" "b" "c"]}, "id-2" {"values" ["a" "b" "c"]}}) 

it's easier do:

(defn extract [key values]   (for [v (get values "values")] {v [key]}))  (->> input      (mapcat (partial apply extract))     (apply merge-with concat)) 

or, without additional function:

(->> (for [[k vs] input]         (for [v (get vs "values")] {v [k]}))      (flatten)      (apply merge-with concat)) 

which works way intended.

the trick wrap key in vector in extract function merge-with concat works without concatenating strings.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -