liveBook · Manning

Sort-by

As explained in Clojure: The Essential Reference

sort-by is a Clojure function that orders collection elements according to comparator results computed from a key function.

sort-by orders a collection by applying a one-argument key function to each element, then comparing the resulting keys. It uses compare by default or accepts an explicit comparator, returning an ordered sequence. section 8.3.5

Sorting by a map key

(sort-by :age [{:age 65} {:age 13} {:age 8}]) ;; ({:age 8} {:age 13} {:age 65}) The key function can also transform values before comparison: (sort-by str [:f "s" \c 'u]) orders unlike values by their string representations.

Use the contract to choose inputs and comparators:

  • Pass a collection supported by seq; transients and scalars are rejected. section 8.3.5
  • Ensure elements or computed keys are mutually sortable, or ClassCastException may result. section 8.3.5

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, input contracts, sortable values, outputs, and comparison exceptions without detailing the sorting algorithm.
Examples
Demonstrates sorting maps by :age, transforming heterogeneous values with str, and using explicit descending comparators.
What it assumes
Assumes familiarity with collections, functions, comparators, and comparable values.
What you can do after
Apply it via Clojure's standard library to produce ordered sequences from collections using derived comparison keys.
How it connects
Connects key functions with comparators, compare, sequences, and Java's Comparator and Comparable interfaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.