How to make max-by in clojure?

If I have a sequence of records defined (defrecord Person [name age]) and I want to get a record about a person with the maximum age, is there an easier way to do this than

 (reduce #(if (> (:age %1) (:age %2)) %1 %2) people) 

This is the only way I have guessed to do this so far, but it looks like it should be a fairly common script that should be built into library functions that make it simpler and / or more general.

+8
clojure
source share
2 answers

clojure.core/max-key is the right tool for the job.

  (apply max-key :age [{:age 12} {:age 20} {:age 30}]) ;; -> {:age 30} 
+12
source share
 (last (sort-by :age [{:age 12} {:age 20} {:age 30}])) 

sorting uses comparison

0
source share

All Articles