If you sort sensor values or attributes with the “sort” filter, they get sorted by their ASCII value. But if you have numbers, the result ist not what you want:
{{ ["5","1","31","23","9","22","11"]|sort }}
gives you [‘1’, ‘11’, ‘22’, ‘23’, ‘31’, ‘5’, ‘9’]. So if you sort for example battery sensors, the list is not in the order you want it. So I developed a “natsort” filter. “natsort” splits text and numbers and sorts the numbers separate from the text.
So
{{ ["5","1","31","23","9","22","11"]|natsort }}
gives you [‘1’, ‘5’, ‘9’, ‘11’, ‘22’, ‘23’, ‘31’].
Another example for testing: battery values:
{{ states.sensor| selectattr('attributes.device_class', 'defined')|selectattr('attributes.device_class', 'eq','battery')|natsort(attribute="state")|list|join("\n\n") }}
If you want to test the natsort filter, download the file core/homeassistant/helpers/template.py at d7913562c42748053cce47f6cba515dfde472433 · martin3000/core · GitHub and replace template.py in homeassistant/helpers/template.py
And you have to install the python natsort module with
pip install natsort
.