O'Reilly logo

Clojure Applied by Alex Miller, Ben Vandgrift

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Grouping Values

The helpful group-by function can group data based on a predicate, returning a map of the predicate result and a sequence of all the matches to that result. For example, we can create an index of planets by their first character:

cljapplied/src/ch3/fn.clj
 
(​defn​ index-planets
 
[planets]
 
(group-by #(​first​ (:name %)) planets))

This function returns a map with keys E, J, M, N, S, U, and V. Each value is a sequence of Planet entities for Earth, Jupiter, Mars and Mercury, Neptune, Saturn, Uranus, and Venus.

One common use of group-by is in combination with a predicate that returns a map of true and false keys when both are needed by the containing code.

For example, if we want to split the planets with moons from those without ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required