Groups values in the map-like object according to the result of a grouping function, returning a new map-based tree.
For example, suppose the data for a set of anime includes a genre field that can have multiple values:
$ cat anime.yaml
- name: "Kaguya-sama: Love is War"
genre:
- Comedy
- Romance
- name: Oshi no Ko
genre:
- Drama
- Slice of Life
- name: Spy x Family
genre:
- Comedy
- name: Wolf Children
genre:
- Drama
- Fantasy
- Slice of Life
The anime can then be grouped by genre:
$ ori "Tree.groupBy(anime.yaml, (anime) => anime.genre)"
Comedy:
- name: "Kaguya-sama: Love is War"
genre:
- Comedy
- Romance
- name: Spy x Family
genre:
- Comedy
Romance:
- name: "Kaguya-sama: Love is War"
genre:
- Comedy
- Romance
Drama:
- name: Oshi no Ko
genre:
- Drama
- Slice of Life
- name: Wolf Children
genre:
- Drama
- Fantasy
- Slice of Life
Slice of Life:
- name: Oshi no Ko
genre:
- Drama
- Slice of Life
- name: Wolf Children
genre:
- Drama
- Fantasy
- Slice of Life
Fantasy:
- name: Wolf Children
genre:
- Drama
- Fantasy
- Slice of Life
In the result tree, the top-level keys for the groups are the individual values found in the genre field: “Comedy”, “Drama”, etc. The group values are arrays containing references to all the items that included that particular genre; a single item can appear in multiple groups.
A common use for groupBy 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.
It’s also common to group items by year or month.