Sorting Two Dimensional Arrays

Yesterday I wrote about how to sort ColdFusion arrays using the static sort() method on the java.util.Arrays object. The original question that inspired the post was actually about sorting 2-dimensional arrays. The answer is that you can sort 2-dimensional arrays using the technique I wrote about yesterday, but only in one dimension.

A ColdFusion 2-dimensional array is actually a java.util.Vector of java.util.Vectors. In other words, if you think of a 2-dimensional array as a table, the rows are Vectors, but the columns are not. If you take a slice of data in any particular column, none of the data is actually in the same data structure because the data actually spans as many Vectors as rows in your column. Maybe a diagram will help:

Array #1: [1][1] [1][2] [1][3] [1][4]
Array #2: [2][1] [2][2] [2][3] [2][4]
Array #3: [3][1] [3][2] [3][3] [3][4]
Array #4: [4][1] [4][2] [4][3] [4][4]

So as you can see, if you want to sort your 2-dimensional array horizontally, you are in luck, but if you want to sort it “by column”, or vertically, I think you will have to massage the data quite a bit first. Probably better to build a query object than a 2-dimensional array, in that case.