5 Replies Latest reply on Oct 5, 2007 2:54 PM by Dan Bracuk

# Compare and Sort a List

I have this list called productColors:
<cfset productColors = "White, Translucent, Slate, Sand, Moss, Merlot, Latte, Black">

And, I have a dynamic list that is not sorted correctly and is a subset of the list above.
So, it might look like this:
"Latte, Black, Sand"

I'd like to end up with this list sorted like the one above:
"Sand, Latte, Black"

How might I write a function to do this?
• ###### 1. Re: Compare and Sort a List  Not sure of a function to do this with. Are these color values in a table? Maybe you could add a sort (sequence) field for each color.

Maybe add the colors to an array and have a sort value for each, then sort the array on that.
• ###### 2. Re: Compare and Sort a List  • ###### 3. Re: Compare and Sort a List  Let's call that these lists L1 (big list), L2 (subset), L3, and L4

<cfset L3 = "">
<cfset L4 = "">

<cfloop list = "#L2#" item = TheItem>
<cfset L3 = ListAppend(L3, ListFind(L1, TheItem))>
</cfloop>
<cfset L3 = ListSort(L3)>

<cfloop list = "#L3#" item = TheItem>
<cfset L4 = ListAppend(L4, ListGetAt(L1, TheItem))>
</cfloop>

or something like that
• ###### 4. Re: Compare and Sort a List  Thanks very much for the response and help getting started. Here's what I've come up with that seems to work:

<cffunction name="cleanAndSortColorList" access="public" output="true">
<!--- The list we want to clean up --->
<cfargument name="L1" type="string" required="yes"/>
<!--- The complete sorted list --->
<cfset L2 = "White,Translucent,Slate,Sand,Moss,Merlot,Latte,Black">
<!--- Use a struct to build a set of the list elements without duplicates--->
<cfset set = StructNew()>
<cfloop index="elem" list="#L1#">
<cfset set[elem] = "">
</cfloop>
<!--- Convert the set back to a list --->
<cfset L1 = StructKeyList(set)>

<cfset L3 = "">
<cfset L4 = "">
<cfloop list = "#L1#" index = TheItem>
<cfset L3 = ListAppend(L3, ListFind(L2, TheItem))>
</cfloop>
<cfset L3 = ListSort(L3,"numeric")>
<cfloop list = "#L3#" index = TheItem>
<cfset L4 = ListAppend(L4, ListGetAt(L2, TheItem))>
</cfloop>
<cfreturn L4>
</cffunction>
• ###### 5. Re: Compare and Sort a List  What's the purpose of converting the list to a structure and then back to a list?