Remove duplicates from a coldfusion array
January 25th, 2007
I needed a way to do this and came up with a version that you can use to even pass in an array of xml objects and it will properly handle it and you can specify which part of the object you want to use in the array.
Code
<cffunction name="removeArrayDuplicates" returnType="array" access="public" hint="Returns the same array but duplicates will be removed">
<cfargument name="inputArray" type="array" required="true">
<cfargument name="optionalObjectName" type="string" required="false" hint="Use dot notation (MyObj.XMLText)">
<cfset var container = StructNew()/>
<cfloop index="i" from="1" to="#ArrayLen(arguments.inputArray)#">
<cfif isDefined("arguments.optionalObjectName")>
<cfset container[Evaluate("arguments.inputArray[i].#arguments.optionalObjectName#")] = ""/>
<cfelse>
<cfset container[arguments.inputArray[i]] = ""/>
</cfif>
</cfloop>
<cfreturn StructKeyArray(container)>
</cffunction>
So to call it on an array just do it like this:
<cfdump var="#removeArrayDuplicates(someXMLSearchResult, 'XMLValue')#">
Sorry, comments are closed for this article.