Lists are a simple way to organize information in a web application. ColdFusion lists are comma-delimited by default. But what if you want to combine two lists using a comma, yet retain the same number of elements as the original list? I'm thinking about names in the format lastname, firstname.

Let's start with these two lists, which we want to combine into a single list of names in the format lastname, firstname:

view plain print about
1<cfset variables.lastNames = "Washington,Adams,Jefferson,Madison,Monroe">
2<cfset variables.firstNames = "George,John,Thomas,James,James">

I hope you will recognize the first five presidents of the United States.

The Long Way

In reality, the long way is not terribly long, but it is repetitive. First we need to combine the list elements together:

view plain print about
1<cfloop from="1" to="#listLen(variables.lastNames)#" index="idx">
2    <cfset variables.names = listAppend(variables.names, "#listGetAt(variables.lastNames, idx)#, #listGetAt(variables.firstNames, idx)#")>
3</cfloop>

A warning on the use of listGetAt: If the target list does not have an element at the referenced position, you will get an error. This loop works because both the lastNames list and the firstNames list have the same number of elements.

Next, we can use two ColdFusion functions, replaceNoCase and listChangeDelims, to manipulate the list delimiters to reach our final format, a semi-colon delimited list of names in the format lastname, firstname:

view plain print about
1<cfset variables.names = replaceNoCase(variables.names, ", ", ";", "ALL")>
2<cfset variables.names = listChangeDelims(variables.names, "~", ",")>
3<cfset variables.names = replaceNoCase(variables.names, ";", ", ", "ALL")>
4<cfset variables.names = listChangeDelims(variables.names, ";", "~")>

The result is:

view plain print about
1Washington, George;Adams, John;Jefferson, Thomas;Madison, James;Monroe, James

That sure was a lot of list manipulation for something that should be easy. Is there an easier way? Of course!

The Short Way

The listAppend function has an optional parameter to specify the delimiter for the newly appended item. Using this parameter results in the elimination of the last four lines of code in the above example:

view plain print about
1<cfloop from="1" to="#listLen(variables.lastNames)#" index="idx">
2    <cfset variables.names = listAppend(variables.names, "#listGetAt(variables.lastNames, idx)#, #listGetAt(variables.firstNames, idx)#", ";")>
3</cfloop>

The result, I believe, is simpler and easier to read code.

ColdFusion has many well designed wheels. As developers, we often do not venture deep enough into the language to see what is available to us and what it can do for us.