1

If I have an array map like this:

{"red" "blue"}

How can I turn this into an array like this:

["red" "blue"]
1
  • 1
    "array" should be "vector". Commented Apr 6, 2014 at 8:04

5 Answers 5

10

Maps hold an unordered set of MapEntry objects, which act like vectors, so just calling first on the map will convert it to a sequence, then grab the first map entry:

(first {"red" "blue"})
; ["red" "blue"]
Sign up to request clarification or add additional context in comments.

1 Comment

You can't get much simpler than this answer!
1
(vec (mapcat seq {"red" "blue"}))
; ["red" "blue"]

Comments

1
user> (vec (apply concat {:a 0 :b 1 :c 2 :d 3}))
[:c 2 :b 1 :d 3 :a 0]

This is similar to Thumbnail's solution, but calling seq is redundant.

Also assumed you mean vector and not array. If having the output just be linear suffices then the call to vec can be eliminated as well.

The problem with the flatten option is if there is internal structure of any sort in the map:

user> (flatten (seq {:a 0 :b 1 :c [2 3]}))
(:c 2 3 :b 1 :a 0)
user> (apply concat {:a 0 :b 1 :c [2 3]})
(:c [2 3] :b 1 :a 0)

Comments

1

If you want to handle empty maps as empty vectors and maps with multiple pairs as a vector of [key val key val...] then you can use reduce into [] or reduce-kv conj [].

so.core=> (reduce into [] {"red" "blue"})
["red" "blue"]
so.core=> (reduce into [] {:a 0 :b 1 :c 2 :d 3})
[:c 2 :b 1 :d 3 :a 0]
so.core=> (reduce into [] {})
[]

Comments

0

One and a very quick way:

(flatten (vec {"red" "blue"}))

=> ("red" "blue")

If you really want an array:

 (into-array (flatten (vec {"red" "blue"})))

 => #<String[] [Ljava.lang.String;@4dc2753>

Keep in mind that in Clojure, ["red" "blue"] is a vector, not an array. And { } means map. Clojure first creates an array map but later, it promotes it to hash map when it is necessary.

1 Comment

Why call vec instead of seq? it is doing a bunch of work (hashing, building a tree) that does nothing for the result. Also flatten is almost never the right thing.

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.