HUGO

Reverse Array

How can I reverse a array in Hugo?

For example, lets say I have the following array:

{{ $myArray := slice "c" "b" "a" }}

I would expect I can do something like:

{{ $myArray := (slice "c" "b" "a") | reverse }}
<!-- Outputs: a b c -->

Any ideas?

layouts/partials/reverse-slice.html

{{- $sliceOriginal := . -}}
{{- $len := len $sliceOriginal -}}
{{- $sliceReversed := slice -}}
{{- range seq $len -}}
  {{- $sliceReversed = $sliceReversed | append (index $sliceOriginal (sub $len .)) }}
{{- end -}}
{{- return $sliceReversed -}}

Then call the partial from a template or shortcode:

{{- $myArray := slice "c" "b" "a" -}}
{{- $myArrayReversed := partial "reverse-slice.html" $myArray -}}

Reference:
https://discourse.gohugo.io/t/how-to-reverse-sort-frontmatter-list/23442/10

3 Likes

Awesome, this works great! Thanks!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.