Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

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 at 5:29:35 PM EDT.

CFML Referenced

StructNew()
<cfscript>
StructSort()
<cfoutput>

Categories

Data Structures

Comments

There are no comments for this entry.