Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator.
user=> (sort-by count ["aaa" "bb" "c"])
("c" "bb" "aaa")
user=> (sort-by first [[1 2] [2 2] [2 3]])
([1 2] [2 2] [2 3])
user=> (sort-by first > [[1 2] [2 2] [2 3]])
([2 2] [2 3] [1 2])
(def x [{:foo 2 :bar 11}
{:bar 99 :foo 1}
{:bar 55 :foo 2}
{:foo 1 :bar 77}])
;sort by :foo, and where :foo is equal, sort by :bar?
(sort-by (juxt :foo :bar) x)
;=>({:foo 1, :bar 77} {:bar 99, :foo 1} {:foo 2, :bar 11} {:bar 55, :foo 2})
(def x [{:foo 2 :bar 11}
{:bar 99 :foo 1}
{:bar 55 :foo 2}
{:foo 1 :bar 77}])
; sort-by given key order (:bar)
(def order [55 77 99 11])
(sort-by
#((into {} (map-indexed (fn [i e] [e i]) order)) (:bar %))
x)
;=> ({:bar 55, :foo 2} {:foo 1, :bar 77} {:bar 99, :foo 1} {:foo 2, :bar 11})
;; Warning: You can sort a Java array and get back a sorted immutable Clojure ;; data structure, but it will also change the input Java array, by sorting it. ;; Copy the array before sorting if you want to avoid this. user=> (def x (to-array [32 -5 4 11])) #'user/x user=> (seq x) (32 -5 4 11) user=> (def y (sort-by - x)) #'user/y ;; Return sorted sequence user=> y (32 11 4 -5) ;; but also modifies x, because it used the array to do the sorting. user=> (seq x) (32 11 4 -5) ;; One way to avoid this is copying the array before sorting: user=> (def y (sort-by - (aclone x))) #'user/y
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
{:added "1.0"
:static true}
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn ^java.util.Comparator comp coll]
(sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
Comments top
No comments for sort-by. Log in to add a comment.