Q:

Last iteration on For loop with If condition with twig

So this is only an example of what I'm trying to achieve.
I'm looping through all items and print only those, who starts with F and separate them with comma.So in the end, the loop will made, for example 15 iterations, but will print only 5.I'm trying to catch the last one that will be printed, so I can remove the comma.I tried with the filter loop.last, but it works only if the loop print the last item, but if the last print was earlier, it's still with comma.
{% for item in items %}
  {% if item starts with 'F' %}
     {{ item }},
  {% endif %}
{% endfor %}

I can't edit anything from items.
Please help, I'v been stuck on this from a while.

A:

A more simply solution could be Adding a condition to the for statement and display the comma only if is not the first interaction (loop.last is defined when using loop conditions). As example:
{% set items = ['Fitem1', 'item2', 'Fitem3', 'Fitem4', 'item5'] %}

{% for item in items if item starts with 'F'%}

{% if loop.first == false  %},{% endif%}
{{item}}

{% endfor %}

See this twigfiddle for the working solutions

A:

I tested this, so I thought I would provide an answer:
{% set items = ['Fitem1', 'item2', 'Fitem3', 'Fitem4', 'item5'] %}
{% set newArray = [] %}
{% for item in items %}
  {% if item starts with 'F' %}
    {% set newArray = newArray|merge([item])  %}
  {% endif %}
{% endfor %}
{{ newArray|join(',') }}

