Using "where" and "sort" with a two dimensional array

Let’s say we have an array like this:

[ [3,f], [6,h], [2,k], [8,l] ]

Now I want to show the second dimension, sorted by the first one. Something like this:

{{ range sort $arr "index . 0" }}
    {{ index . 1 }}
{{ end }}

Unfortunately, it doesn’t work. Any idea how I can do this?

Not the nicest solution but you can create a partial that converts a slice to dict:


{{ return (dict "key" (index . 0) "value" (index . 1)) }}

then apply it like a function and sort by the key:

{{ range sort (apply $arr "partial" "slice-to-dict.html" ".") "key" }}
  <p>{{ .value }}</p>
{{ end }}

Unfortunately you cannot define the partial in-line with “define”, since “template” cannot be used as a function to “apply” with nor can it return any value like partials can.


Thanks! It’s very interesting.

While waiting for help, I used a workaround: I added a condition inside the range to filter the values for a single one, and then I put that block of code inside a loop to go through the values. It works fine, considering the fact that I don’t have to be worried about performance!

Nevertheless, your solution will be very helpful to me, especially for more complicated scenarios.