For(of) last item

Hi All,

When using a stache for(of) helper, is there a way to know when the current item is the last (or not the last) in the list?

Cheers
Rob

If you’re iterating over an array, you can use scope.index to get the index of the current item, and compare that to the length of the list.

You could create a helper like this:

stache.addHelper("last", (index, length) => index === length - 1);

Then you can use this in your view:

    {{#for(item of itemsArray)}}
      <p {{#if( last(scope.index, itemsArray.length) )}}class="last"{{/if}}>{{item}}</p>
    {{/for}}

Hi Kevin,
That’s genius, super simple and works like a charm!

Thanks
Rob

1 Like

You could also do a minusOne helper and use it like:

{{# eq( scope.index, minusOne( itemsArray.length ) ) }}

Created an idea for making this even easier here: https://github.com/canjs/can-stache/issues/674