Math manipulation on arrays

In home assistant jinja code, it seems that it is possible to apply multiplication to each element of an array using the map function:

{% set numbers = [2, 4, 6, 8] %}
{{ numbers | map('multiply', 2) | list }}

The output of this statement is:

[
4,
8,
12,
16
]

Now it would seem logical that you could do the same for the other maths functions too such as divide, eg.:

{% set numbers = [2, 4, 6, 8] %}
{{ numbers | map('divide', 2) | list }}

but this fails with the error:

TemplateRuntimeError: No filter named ā€˜divideā€™

This seems to be the case for divide, add and minus, with only multiply working. Why only support one function?

I get that normally we can use mathematical symbols (+, -, *, /) but how do we use these with arrays?

Jinja2 's Built-in filters

If you want to divide by 2, multiply by 0.5.

If you want to add/subtract, youā€™ll need to use a for-loop.

Thanks for your answer, but frankly, thatā€™s crazy!

The one line array manipulation is so elegant, I canā€™t believe it only supports one out of four maths operators (and a second with the inelegant workaround of multiplying by the inverse, as you pointed out)

The four math operators are pretty basic stuff. They really should be supported!

Jinja is an open-source project so feel free to contribute/comment there.

It looks as though multiply isnā€™t documented ā€” itā€™s not on the Jinja page, I canā€™t find it in their repository, and it isnā€™t a Python method on intā€¦

:thinking:

Edit: Found it in HA. Currently line 1520 of this file:

Looks easy to submit a PR for add and others.

Only took me seven months to work it out, but hereā€™s a faked-up add filter:

{{ [1,2,3,4]|batch(1)|map('sum',start=5)|list }}
4 Likes

Thanks! Nice work! :+1:t3:

I was unfamiliar with the batch filter and the online examples focused on its ability to reformat HTML tables so I failed to grasp its utility for Home Assistant applications. However, your example makes me understand its strength is its ability to generate a ā€œlist of listsā€. That allows map to be applied to each item in the original list.

Thanks again for this useful example.

1 Like

Iā€™ve submitted a PR to add add ā€” letā€™s see what happens.

1 Like

You are a genius!

1 Like

Just dropped in 2024.6. We can now do things like array conversion of Ā°C to Ā°F:

{{ [-40, -18, 0, 100]
   |map('multiply', 1.8)
   |map('add', 32)
   |map('int')
   |list }}

The documentation now includes multiply and add at the end of this section:

3 Likes