Filter an array of ASCII words based on word length

I have a list of words in site data. I.e., in a file named states.json, the data might look like this:

{"dictionary":["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]}

I am trying to make filters that capture 10-letter words, 9-letter words, 8-letter words, and so forth. My data will not be consistent though, so I don’t know in advance what the longest word length is in a given data file.

I’m seeking a solution to be able to capture the series of word lengths. I tried this just to find all 5-letter words:

{{ $data := .Site.Data.states }}
{{ $v5 := where $data.dictionary ". | len" "==" 5 }}
{{ $v5 }}

It returns zero results (empty array). I’ve tried some different variations on that too, but nothing’s working for me.

  1. What is the correct way to “filter” all of the words that have a specific length?
  2. Is there a way to make a “map” such that I could process the entire list at once, and add each word to a map property that indicates the word length. I.e., so my template logic could be {{ mymap.fiveLetter }} to get all five-letter words (or something like that)?

What’s a smart way to handle this considering the longest word in any given data set will be variable (in some datasets the longest word is 12 letters, and in others it’s 10 letters)?

Create an array of maps, where each map contains the value and length.

{{ $s := slice "a" "bc" "def" "ghi" }}

{{ $words := slice }}
{{ range $s }}
  {{ $words = $words | append (dict "word" . "length" (len .)) }}
{{ end }}

{{ range where $words "length" 3 }}
  {{ .word }}  --> def ghi
{{ end }}
1 Like

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