Tree.

groupBy(map, fn)

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.

g 0 [data for Kaguya-sama] ->0 0 1 [data for Oshi no Ko] ->1 1 2 [data for Spy x Family] ->2 2 3 [data for Wolf Children] ->3 3
g Comedy/ ->Comedy/ Comedy/ Drama/ ->Drama/ Drama/ Fantasy/ ->Fantasy/ Fantasy/ Romance/ ->Romance/ Romance/ Slice of Life/ ->Slice of Life/ Slice of Life/ Comedy/0 [data for Kaguya-sama] Comedy/->Comedy/0 0 Comedy/1 [data for Spy x Family] Comedy/->Comedy/1 1 Drama/0 [data for Oshi no Ko] Drama/->Drama/0 0 Drama/1 [data for Wolf Children] Drama/->Drama/1 1 Fantasy/0 [data for Wolf Children] Fantasy/->Fantasy/0 0 Romance/0 [data for Kaguya-sama] Romance/->Romance/0 0 Slice of Life/0 [data for Oshi no Ko] Slice of Life/->Slice of Life/0 0 Slice of Life/1 [data for Wolf Children] Slice of Life/->Slice of Life/1 1
Input map
Grouped by genre

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.