This function creates a new tree that groups values according to the result of a grouping function.
For example, suppose the data for a set of books includes a genre
field that can have multiple values:
$ cat books.yaml
- title: "1984"
author: "George Orwell"
genre:
- "Sci-Fi"
- title: "Pride and Prejudice"
author: "Jane Austen"
genre:
- "Romance"
- title: "Jane Eyre"
author: "Charlotte Brontë"
genre:
- "Romance"
- "Gothic"
- title: "Frankenstein"
author: "Mary Shelley"
genre:
- "Sci-Fi"
- "Gothic"
- title: "The Time Traveler's Wife"
author: "Audrey Niffenegger"
genre:
- "Romance"
- "Sci-Fi"
The books can then be grouped by genre. Here the =_/genre
function is shorthand for (book) => book/genre
. This function lets the group
built-in know what the books should be grouped by.
$ ori group books.yaml, =_/genre
Sci-Fi:
- title: "1984"
author: George Orwell
genre:
- Sci-Fi
- title: Frankenstein
author: Mary Shelley
genre:
- Sci-Fi
- Gothic
- title: The Time Traveler's Wife
author: Audrey Niffenegger
genre:
- Romance
- Sci-Fi
Romance:
- title: Pride and Prejudice
author: Jane Austen
genre:
- Romance
- title: Jane Eyre
author: Charlotte Brontë
genre:
- Romance
- Gothic
- title: The Time Traveler's Wife
author: Audrey Niffenegger
genre:
- Romance
- Sci-Fi
Gothic:
- title: Jane Eyre
author: Charlotte Brontë
genre:
- Romance
- Gothic
- title: Frankenstein
author: Mary Shelley
genre:
- Sci-Fi
- Gothic
In the result tree, the top-level keys for the groups are the individual values found in the genre
field: “Sci-Fi”, “Romance”, and “Gothic”. The group values are arrays containing references to all the books that included that particular genre; a single book can appear in multiple groups.
A common use for group
comes up anywhere content is tagged. For example, a blog with posts that can have multiple tags may want to offer a /tags
area showing blog posts grouped by tag.