How do I sort a structure?
Use the built in ColdFusion structSort() function.
<cfscript>
foo = structNew();
StructInsert(foo, "a", "this");
StructInsert(foo, "b", "is");
StructInsert(foo, "c", "a");
StructInsert(foo, "d", "test");
</cfscript>
StructSort() returns an array of top-level key names (strings).
<cfoutput>#arrayToList(structSort(foo))#</cfoutput>
You can also sort parent structures based on their child structures. For example, the following example will sort all of the people in foo by their age:
<cfset foo = structNew()>
<cfset foo.raymond = structNew()>
<cfset foo.raymond.age =9>
<cfset foo.raymond.lastname = "Camden">
<cfset foo.jeremy = structNew()>
<cfset foo.jeremy.age =10>
<cfset foo.jeremy.lastname = "Petersen">
<cfset foo.joe = structNew()>
<cfset foo.joe.age =12>
<cfset foo.joe.lastname = "Test">
<cfoutput>#arrayToList(structSort(foo, "numeric", "asc", "age"))#</cfoutput>
This question was written by Jeremy Petersen
It was last updated on May 15, 2006.