Removing Duplicate List Items in ColdFusion

Today I ran into an issue of having duplicate items in my list which I had to get rid of.

I’ve seen people looping through and adding items to another list or using Arrays to remove the duplicates but all of those seem to over complicate things.

A quick and efficient way to remove duplicates in a list is by using Structs.

<cfset myList = "orange,banana,apple,orange,cherry,strawberry,banana,pineapple,kiwi,cherry,pear,banana" />
<cfset tempStruct = structNew() />

<cfloop list="#myList#" index="item">
	<cfset tempStruct[item] = item />
</cfloop>

<cfset myListNoDuplicates = structKeyList(tempStruct) />
<cfdump var="#myListNoDuplicates#" />

This works because Structs cannot have duplicate keys. In the above example we are using the actual list item as a key.

As a result we get a struct without any duplicates. Finally we just need to convert it back to a list by using structKeyList and you’re done!

Leave a comment