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

group-by

clojure.core

  • (group-by f coll)
Returns a map of the elements of coll keyed by the result of
f on each element. The value at each key will be a vector of the
corresponding elements, in the order they appeared in coll.

2 Examples top

  • user=> (group-by count ["a" "as" "asd" "aa" "asdf" "qwer"])
    {1 ["a"], 2 ["as" "aa"], 3 ["asd"], 4 ["asdf" "qwer"]}
    
    user=> (group-by odd? (range 10))
    {false [0 2 4 6 8], true [1 3 5 7 9]}
    
  • ;; group by a primary key
    user=> (group-by :user-id [{:user-id 1 :uri "/"} 
                               {:user-id 2 :uri "/foo"} 
                               {:user-id 1 :uri "/account"}])
    
    {1 [{:user-id 1, :uri "/"} {:user-id 1, :uri "/account"}],
     2 [{:user-id 2, :uri "/foo"}]}
    
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:5541 top

(defn group-by 
  "Returns a map of the elements of coll keyed by the result of
  f on each element. The value at each key will be a vector of the
  corresponding elements, in the order they appeared in coll."
  {:added "1.2"}
  [f coll]  
  (persistent!
   (reduce
    (fn [ret x]
      (let [k (f x)]
        (assoc! ret k (conj (get ret k []) x))))
    (transient {}) coll)))
Vars in clojure.core/group-by: assoc! conj defn fn get let persistent! reduce transient

Comments top

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