How to Sort a Multi-Dimensional Array?
Monday, March 17th, 2008The reason for handling multiple dimensions is simply that it happens many times those are the arrays we have and have to sort.
arEvents(0, 0) = 1
arEvents(1, 0) = “01-12-2004″
arEvents(2, 0) = “Event #1″
arEvents(0, 0) = 2
arEvents(1, 0) = “10-16-2004″
arEvents(2, 0) = “Event #2″
arEvents(0, 0) = 3
arEvents(1, 0) = “02-13-2004″
arEvents(2, 0) = “Event #3″
It could be sorted by simply handing it off to the arraySort() function, specifying which dimension to sort it by (in this case the date).
ArEvents = arraySort( arEvents, 1, true )
And then here’s the function that’s responsible for it all.
function arraySort( arToSort, sortBy, compareDates )
Dim c, d, e, smallestValue, smallestIndex, tempValue
For c = 0 To uBound( arToSort, 2 ) - 1
smallestValue = arToSort( sortBy, c )
smallestIndex = c
What’s happening here is that we’re going through the array one item at a time. With each item, we’ll use the sortBy parameter, find the current item, and set the smallest value and index placeholders to the current item. Then we take these items, or placeholders, and compare them to EACH item in the array and look for a smaller value.
For d = c + 1 To uBound( arToSort, 2 )
if not compareDates then
So if the compareDates flag has been set to false, the function will try to compare the values as strings using the inbuilt strComp() function of ASP. Now, don’t be too worried about numbers, they will be handled perfectly with this function as well. When we use the strComp() function, it will produce a -1 if the compared string (the first parameter) is smaller, a zero if they’re equal, and a 1 if it’s larger/greater. In this case, as we’re sorting depending on smaller values, we would then set the placeholders to this value and index, if we find that it is indeed smaller. Now you’re probably beginning to see where modifications could be made to sort in a descending order.
if strComp( arToSort( sortBy, d ), smallestValue ) < 0 Then
smallestValue = arToSort( sortBy, d )
smallestIndex = d
End if
So here we’ve got the code to handle dates, if the compareDates flag has been set to true. Of course we first check and ensure that we truly are dealing with dates. If not, we recurse, and come back through just comparing strings.
Posted by Mahesh ( Tryangled )