Remove duplicates from an array

Hi,

I can’t wrap my head around how to eliminate duplicates in array. I have this fn which trasverse local files.

	{{- $files := readDir (print "/static/gallery/" .) }}

Now in $files variable I have a list of all images for a gallery, the problem is I have many versions of the same image:

IMG_4472-1280px.jpg
IMG_4472-1280px.webp
IMG_4472-1920px.jpg
IMG_4472-1920px.webp

So I narrowed down only to file name by spliting the string:

{{- range $files -}}
 {{- $split := split .Name "-" -}}
 {{- $image := index $split 0 -}}
{{- end -}}

Now how can remove duplicates and/or push the unique filenames to a new array? Or is there a better method of doing this?

Thanks!

You have two options:

  1. https://gohugo.io/extras/scratch/ See SetInMap and GetSortedMapValues … I think this will be your best bet.
  2. Also see the uniq template func.

Thanks! Scratch will do the job.