nobby
1
Given front matter that looks like this:
[[item]]
number = 1
[[item]]
number = 2
[[item]]
number = 3
Is there a function to determine the smallest and biggest number?
I’m doing the following to calculate the average:
{{$counter := 0}}
{{$total := 0}}
{{range .item}}
{{$counter = add $counter 1}}
{{$total = (add $total .number)}}
{{end}}
{{div $total $counter}}
The number of items is variable.
ju52
2
not tested 
{{ range .Item sort "value" "Number" }} // Don't know if this works
The first value is the minimum, the last the maximum.
1 Like
zwbetz
3
Expanding on @ju52’s answer:
- create an empty slice
- range through your front matter, adding each number to the slice
- sort the slice (default sort is ascending order)
- use
first
function to get the min
- use
last
function to get the max
- or
index
function at slice len
minus 1
2 Likes
zwbetz
4
For future readers, code examples of the above:
{{ $list := slice 0 5 1 4 2 3 }}
{{ printf "Unsorted list: %d" $list }}
{{ $list := sort $list }}
{{ printf "Sorted list: %d" $list }}
{{ $min := index $list 0 }}
{{ printf "Min: %d" $min }}
{{ $length := len $list }}
{{ printf "Length: %d" $length }}
{{ $last_index := sub $length 1 }}
{{ printf "Last index: %d" $last_index }}
{{ $max := index $list $last_index }}
{{ printf "Max: %d" $max }}
Output:
Unsorted list: [0 5 1 4 2 3]
Sorted list: [0 1 2 3 4 5]
Min: 0
Length: 6
Last index: 5
Max: 5
3 Likes
nobby
5
Thanks for putting that together. I’m still making a few changes, but here’s my implementation in case it helps anyone.
{{$counter := 0}}
{{$number := slice}}
{{$total := 0}}
{{range .item}}
{{$counter = add $counter 1}}
{{$number = $number | append .number}}
{{$total = add $total .number}}
{{end}}
{{$number := sort $number}}
avg: {{div $total $counter}}
min: {{index $number 0}}
max: {{index $number (sub $counter 1)}}
1 Like
bep
6
$min := 0
$max := 0
$total := 0
$count := len .item
range .item
$total = add $total .number
if gt .number $max
$max = .number
if lt .number $min
$min = .number
2 Likes