1

I have a nested map which looks something like this:

{"a" {:points 2} "b" {:points 7} "c" {:points 1} "d" {:points 3}}

And I would like to turn it into a sequence of a maps in order to sort (with sort-by) and print it afterwards.

({:name "a" :points 2}
 {:name "b" :points 7}
 {:name "c" :points 1}
 {:name "d" :points 3})

From the documentation I figured that I will need something like postwalk but I can't wrap my head around it.

1
  • I really liked mobytes answer. I provided an alternate for your pleasure ;) Commented Jan 1, 2013 at 17:38

3 Answers 3

6
(sort-by :name
         (map #(conj {:name (key %)}
                      (val %))
              {"a" {:points 2}
               "b" {:points 7}
               "c" {:points 1}
               "d" {:points 3}}))

-> ({:points 2, :name "a"}
    {:points 7, :name "b"}
    {:points 1, :name "c"}
    {:points 3, :name "d"})
Sign up to request clarification or add additional context in comments.

Comments

2

If your goal is to print it in sorted order, why not simply put it into a sorted map? (into (sorted-map) m).

Comments

2

I'd suggest something like:

(sort-by :name 
  (for [[n m] my-map] 
    (into m {:name n})))

This makes use of a few handy techniques:

  • Destructuring to break my-map into [key value] pairs
  • The fact that you already have maps in the values, so you can use into to add to them
  • A for comprehension to build the list
  • sort-by to sort the final results

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.