Psyren
Psyren

Reputation: 13

Parsing key-value pairs for sorting in clojure

I want to sort a given sequence of maps by using one of the keys, Cost:

({:Date "2012-12-01", :Cost "11.23"} {:Date "2012-12-02", :Cost "25.68"} {:Date "2012-12-03", :Cost "20.55"} {:Date "2012-12-04", :Cost "50.22"})

However, I don't want to do the sort while the value for :Cost is a string. I initially tried by using the (sort-by) function using the key :Cost but the sort is doing string comparisons instead of double comparisons. Is there a way to parse the values for :Cost from strings to doubles in a sequence of maps? I'm relatively new to Clojure and functional programming and any help is greatly appreciated.

Upvotes: 1

Views: 182

Answers (1)

Lee
Lee

Reputation: 144126

You can use Double/parseDouble:

(sort-by #(Double/parseDouble (:Cost %)) input-list)

Upvotes: 3

Related Questions