Katherine
Katherine

Reputation: 47

In Clojure, how do I sort a set of maps by a key within a value?

This is an awkward question to phrase, but say I have a set of maps like so:

(def person-1 {:name "Joshua" :birthday {:day 5 :month 12 :year 1960}})
(def person-2 {:name "Louise" :birthday {:day 17 :month 4 :year 1987}})
(def person-3 {:name "Jessica" :birthday {:day 28 :month 5 :year 1972}})

(def people #{person-1 person-2 person-3})

How would I sort people by their birth month, for example?

I know that I could just do (sort-by :name people) if I wanted to sort by name, but I'm not sure, syntactically, how the example above would work.

Upvotes: 0

Views: 438

Answers (3)

Another option is to use an anonymous function:

(sort-by #(:year (:birthday %)) people)

Share and enjoy.

Upvotes: 0

DJG
DJG

Reputation: 6543

Try:

(sort-by (comp :year :birthday) people)

this sorts on the person's year of birth.


comp takes a list of functions and composes them into a single function that first takes the parameter, runs the function on the right first, takes the result and then proceeds leftward.

See comp in ClojureDocs for details.

Upvotes: 2

zcaudate
zcaudate

Reputation: 14258

sort-by takes a function as it's first argument, so you can do:

(sort-by (fn [m] (-> m :birthday :month)) people)

Upvotes: 1

Related Questions