How do I sort a 2 dimensional array?

ColdFusion does not provide a built-in way to sort a multi-dimensional array. However, there 2 ways to accomplish this task.

1) Turn the multi-dimensional array into a query and then use query of queries to sort it.

<!--- sample array --->
<cfset arr = arrayNew(2)>
<cfset arr[1][1] = "beta">
<cfset arr[2][1]  = "bar">
<cfset arr[3][1]  = "foo">
<cfset arr[4][1]  = "alpha">
<cfset arr[1][2]  = "car">
<cfset arr[2][2] = "boat">
<cfset arr[3][2] = "bike">
<cfset arr[4][2] = "car">
<!--- convert array to CF query --->
myQuery = QueryNew("one,two");
for (i=1; i LTE ArrayLen(arr); i=i+1) {
	newRow = QueryAddRow(myQuery);
	QuerySetCell(myQuery, "one", #arr[i][1]# );
	QuerySetCell(myQuery, "two", #arr[i][2]# );
<cfdump var= #myQuery#>
<!--- Sort --->
<cfquery name="qSort"
dbtype = "query">
FROM myQuery
<cfdump var= #qSort#>
  1. You can sort single dimension arrays use the built in ColdFusion function arraySort(). So with this in mind, you can pull the array dimension you want to sort by into its own single dimension array and then use arraySort() on this single dimension array.
var sortArray = ArrayNew(1);
for (i=1; i LTE ArrayLen(arrayToSort); i=i+1) {
	ArrayAppend(sortArray, arrayToSort[i][sortColumn]);

It is then a simple matter of reordering the rest of your multi-dimensional array based on the new sort order of the single dimension array.

	theList = ArrayToList(sortArray);
	ArraySort(sortArray, type, order);
	for (i=1; i LTE ArrayLen(sortArray); i=i+1) {
		thePosition = ListFind(theList, sortArray[i]);
		theList = ListDeleteAt(theList, thePosition);
		for (j=1; j LTE ArrayLen(arrayToSort[thePosition]); j=j+1) {
			arrayToReturn[counter][j] = arrayToSort[thePosition][j];
		ArrayDeleteAt(arrayToSort, thePosition);
		counter = counter + 1;

The above code was taken from Robert West's ArraySort2D() function that can be found at:

This question was written by Jeremy Petersen
It was last updated on May 8, 2006.


Data Structures


comments powered by Disqus