Find highest number in loop

Does anyone know if / how it’s possible to find the highest and lowest number in a HubDB loop? I have a list of values displayed inside a table and I require the number to change colour via CSS if it’s the highest / lowest.

Hi @ben-duchy,
I used my doggie HubDB demo from before for this

{% set table = hubdb_table_rows(module.hubdbtable_field) %}

{% set weight_array = [] %}
{% for row in table %}
{% do weight_array.append( row.weight) %}
{% endfor %}
{% set sorted_array = weight_array|sort %}

{% for row in table %}
{{ row.name }}<br>
{{ row.weight }} {% if row.weight == sorted_array[0] %}is lowest{% elif row.weight == sorted_array[-1] %}is highest{% endif %}

<hr>
{% endfor %}

The sorted_array sorts the numbers lowest to highest, then you test your displayed values against sorted_array[0] (lowest) and sorted_array[-1] (highest)

I’m sure there’s other ways of doing it.


Barry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

Hi @ben-duchy,

I don’t quite understand the exact implementation plan, but you can do the following if it’s just a matter of finding the highest/lowest numbers in a loop.

Create two variables before the loop: highest and lowest

In your loop, always compare the current row’s data against the highest and lowest variables. If the value is higher/lower, then update the variable with this row’s data.

Once the loop ends, you’ll have two usable variables to target the exact hubDB rows.

Thanks @GiantFocal, sounds like you’re on the same page as @BarryGrennan.

Might be a bit more logic for my particular use case, but it gives me a good starting point.