Search code examples
sequencefreemarker

freemarker sequence index calculation


Been banging my head on this for the past day or so, and im not sure what the issue is. Would be good to get some fresh eyes on it to let me know what im doing wrong.

Im trying to loop through a sorted sequence of strings in freemarker, and pull out duplicates to store in a new sequence. The duplicates are what i want, not uniques.

<#assign dupMessageids = [] />
<#list arrMsdIds as itemId>
        <#assign currIndex = itemId?index />
        <#if arrMsdIds[(currIndex?number)+1]==itemId>
            <#assign dupMessageids = dupMessageids + [itemId] />
        </#if>
</#list>

Also tried this expression without success:

arrMsdIds[currIndex+1]==itemId

So im checking if the current indexed item is equal to the item next to it in the sequence. But am getting this error:

The following has evaluated to null or missing: ==> arrMsdIds[(currIndex?number)+1]

Any help would be greatly appreciated


Solution

  • As of the error you get, when you reach the index of the last item, currIndex + 1 will point after the last item, hence, that item is missing. Anyway, here's the fixed version with some prettifying.

    <#assign dupMessageIds = []>
    <#list arrMsdIds as itemId>
      <#if itemId?has_next && arrMsdIds[itemId?index + 1] == itemId>
        <#assign dupMessageIds += [itemId] />
      </#if>
    </#list>
    

    But note the templates aren't designed to deal with stuff like this. They meant to show data that was already "calculated" in a real language. In particular, don't do the above if you have hundreds of duplicates, as the resulting sequence will be very slow to read (yes, to read).