Template - Sort entities by state (value, not name)

I’m trying to list all my batteries, sorted by battery state.
For now, only the “sorting” part.

{% set sorted_list = 
  "group.zigbee_batteries" | expand | sort(attribute='state')
%}
{% for state in sorted_list %}
{{ state.entity_id }} : {{ state.state }}
{%- endfor -%}
------------------
sensor.porte_terrasse_power : 100
sensor.weather_bureau_power : 100
sensor.weather_chambre_power : 100
sensor.remote_tradfri_bureau_power : 87
sensor.weather_terrasse_power : 88
sensor.weather_salon_power : 98

This sorts by string (stringized integer), not by value : “100” is before “87” before it start with 1.

How can it be done ?
Thanks a lot !!

Did you ever figure this out? Trying the same thing…

Nope, sorry. I’m doing it with a custom card.

1 Like

I have a similar problem, in my case I just need the minimum value for the “cost”.
I found a workaround, but an excessively complicated one.
The way I did it, was to “manually” compare all the values in the data vector and store the position for the minimum in the result.

{% set data = namespace(sensors=[]) %}
{% for cost in states.sensor %}
  {%- if "dia" in cost.entity_id.replace("diario", "") and "custo" in cost.entity_id and not "dia_" in cost.entity_id -%}
    {% set data.sensors = data.sensors + [cost] %}
  {%- endif -%}
{% endfor %}

{% set result = 0 %}
{% for i in range(expand(data.sensors)|map(attribute='state')|list|length) %}
  {% if i > 0 and (expand(data.sensors)|map(attribute='state')|list)[i]|float < (expand(data.sensors)|map(attribute='state')|list)[result]|float -%}
    {% set result = i %}
  {%- endif -%}
{% endfor %}

After that, I just use the result value to return the position of the vector with the attribute I need.

{{ (expand(data.sensors)|map(attribute='name')|
list)[result]}}

Someone please let me know if there’s a simpler or more efficient way to do this.