Jinjia: how to sort entities by "area"?

Please help with jinja.

Assume we need to sort entities by some attribute:

{{ states.some_domain |
   sort(attribute='some_attribute') |
   map(attribute='entity_id') |
   list }}

But what if we need to sort by “area” - which is not an attribute (a real WTH for me) ?

Here is how I tried to do it:

{% set ns = namespace(entity_and_area=[]) -%}
{%- for entity in states.light -%}
  {%- set entity_id = entity.entity_id -%}
  {%- set area = area_name(entity.entity_id) -%}
  {%- set entity_and_area = ({'entity_id':entity_id,'area':area}) -%}
  {%- set ns.entity_and_area = ns.entity_and_area + [entity_and_area] -%}
{%- endfor -%}
{%- set sorted_list = (ns.entity_and_area) | sort(attribute='area') -%}
sorted_list = {{sorted_list}}

Is it possible to minimize this cumbersome code?

You can reduce that code a bit:

{% set ns = namespace(ea=[]) -%}
{%- for e in states.light -%}
  {%- set ns.ea = ns.ea + [({'entity_id':e.entity_id,'area':area_name(e.entity_id)})] -%}
{%- endfor -%}
{%- set sorted_list = (ns.ea) | sort(attribute='area') -%}
sorted_list = {{sorted_list}}

A one-liner that might give some ideas: this gives a list containing a list of entities within each area, where the areas are sorted alphabetically but not shown, for all areas where you have a light :crazy_face::

{{ states.light|map(attribute='entity_id')|map('area_name')|list|sort|map('area_entities')|list }}

Dictionary with areas (where you have a light) as keys and a list of all entities therein as values:

{% set al = states.light|map(attribute='entity_id')|map('area_name')|reject('none')|unique|list|sort %}
{% set ns = namespace(ad={}) %}
{% for a in al %}{% set ns.ad = dict(ns.ad, **{a:area_entities(a)}) %}{% endfor %}
{{ ns.ad }}

Waiting for one of the gurus to swoop in and solve it in about 16 characters…

2 Likes