Count unique data item values

For example, you want to know the number of years when books have been published.

data/books.yml:

- Book: "Book1"
  Year: "2020"
- Book: "Book2"
  Year: "2020"
- Book: "Book3"
  Year: "2021"

template:

{{ $scratch := newScratch }}
{{ range .Site.Data.books }}
  {{ $scratch.Add "years" (slice .Year) }}
{{ end }}
{{ len ($scratch.Get "years" | uniq) }}

This will return 2, as books have been published in 2020 and 2021.

1 Like

A variant:

{{ apply .Site.Data.books "index" "." "Year" | uniq | len }}
8 Likes

The beauty of one liners… Thanks!