HUGO

Iterate over map, return unique values with a tally

I have a csv file that looks like.

section1, stable
section2, draft
section4, unknown
section5, testing
section6, stable
set,stable

I would like to create a pie chart from it without hardcoding how many times for example, the value stable occurs.

I’m looking for a function or maybe a way to iterate through csv file and return a map of [ uniqueValue tally] of type map[string]int.

Using the above csv file as an example, I would be looking to return ["stable" 3 "draft" 1 "unknown" 1 "testing" 1]

I would also settle for a slice too, i.e [3,1,1,1]. Looking for ideas. Thank you.

Structure

content/
└── post
    └── test
        ├── foo.csv
        └── index.md

content/post/test/foo.csv

section1, stable
section2, draft
section4, unknown
section5, testing
section6, stable
set,stable

layouts/_default/single.html

{{- define "main" -}}

  {{- $csv := .Resources.GetMatch "*.csv"  -}}
  {{- if $csv -}}

    {{- $valuesMap := dict -}}
    {{- range (transform.Unmarshal $csv) -}}
      {{- $value := trim (index . 1) " " -}}
      {{- with index $valuesMap $value -}}
        {{- $valuesMap = merge $valuesMap (dict $value (add 1 .)) -}}
      {{- else -}}
        {{- $valuesMap = merge $valuesMap (dict $value 1) -}}
      {{- end -}}
    {{- end -}}

    {{- range $k, $v := $valuesMap -}}
      {{ $k }} = {{ $v }}<br>
    {{- end -}}

  {{- end }}

{{- end }}

Output

draft = 1
stable = 3
testing = 1
unknown = 1

1 Like

Thanks @jmooring, this gives me a huuge headstart. I will build on it.