Ask a Jedi: Sorting a 2D Array

Pat asks:

Is there an easy way to 'sort' a two dimensional array ? I know you can use ArraySort() on a single dimensional array. For example: I have a two dimensional array that has a reference number in element 1 (which refers to a supplier in a database), in element 2 is a calculated distance from a supplied postcode. The array is produced in the order that suppliers are retrieved from the database. However, it would be better to sort the array by distance before outputting the data.

As Pat mentions, there is indeed an arraySort function built into ColdFusion, but it sorts single dimension arrays only. One way of handling this is with a bubble sort implementation. I found a good example of this on Nathan Stanford’s site. Here is a quick example:

<cfset data = arrayNew(2)> <cfset data[1][1] = “Alpha”> <cfset data[1][2] = 9> <cfset data[2][1] = “Beta”> <cfset data[2][2] = 1> <cfset data[3][1] = “Gamma”> <cfset data[3][2] = 12>

<cfdump var=”#data#”>

<cfloop index=”outer” from=”1” to=”#arrayLen(data)#”> <cfloop index=”inner” from=”1” to=”#arrayLen(data)-1#”> <cfif data[inner][2] gt data[outer][2]> <cfset arraySwap(data,outer,inner)> </cfif> </cfloop> </cfloop>

<cfdump var=”#data#”> </code>

You will notice the code is rather simple. We loop over the array with an outer and inner loop, doing comparisons as we run through the data. If you read the wikipedia article you will see that this sort isn’t the best for large sets of data. Another option then would be to simply create the data into a query. You probably had the data in a query already. If not, you can make one with queryNew. At that point, the sorting becomes a trivial matter of using a query of query.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments