You're viewing version 1.2.0 of sort-by. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

sort-by

clojure.core

  • (sort-by keyfn coll)
  • (sort-by keyfn comp coll)
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.

6 Examples top

  • 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])
  • user=> (sort-by :rank [{:rank 2} {:rank 3} {:rank 1}])
    ({:rank 1} {:rank 2} {:rank 3})
  • (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})
  • ;sort entries in a map by value
    user=> (sort-by val > {:foo 7, :bar 3, :baz 5})
    ([:foo 7] [:baz 5] [:bar 3])
  • ;; 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
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2343 top

(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"}
  ([keyfn coll]
   (sort-by keyfn compare coll))
  ([keyfn ^java.util.Comparator comp coll]
   (sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
Vars in clojure.core/sort-by: comp compare defn fn sort

Comments top

No comments for sort-by. Log in to add a comment.