Search code examples
loopscoldfusioniterationcfloop

Coldfusion Order on alphabet


I'm looping over an iteration like this :

<cfloop condition="depFeedIterator.hasNext()">
    <cfset item=depFeedIterator.next()/>
    <ul><li>#item.getValue('title')</li></ul>
</cfloop>

This returns me all the titles. But I have to organize these titles on alphabetic order ( this has been done in the bean itself ). So I've added this:

<cfif #left(#item.getValue('title')#,1)# == "a">
    <li><h2>A</h2></li>
       etc

But if I have two titles starting with an A i get this:

A
Abc

A
Aab

instead of :

A
Abc
Aac

I've been playing with this a while and couldnt figure it out. I hope you guys have some advise


Solution

  • You need to track the previous letter too, and only output the heading when the current letter is different from the previous one, eg:

    <cfset prevFirstLetter = "">
    <cfloop condition="depFeedIterator.hasNext()">
        <cfset item=depFeedIterator.next()/>
        <cfset itemTitle = item.getValue('title')>
        <cfset currentFirstLetter = left(itemTitle,1)>
        <cfif currentFirstLetter NEQ prevFirstLetter>
            <li><h2>#currentFirstLetter#</h2></li>
            <cfset prevFirstLetter = currentFirstLetter>
        </cfif>
        <!--- etc --->
    </cfloop>
    

    You also might benefit from reading "When to use pound-signs", regarding pound-sign usage.