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 ...

Get Clojure Applied now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.