How to Sort a Multi-Dimensional Array - Conclusion
(Page 4 of 4 )
So that is the wonderful, magical function with all of its very limited glory. If you decide you want to try sorting in the reverse direction (descending), then you've probably already figured out where you need to add code. If not, I'll give you a hint: it is only a matter of passing in another parameter to the function (the direction), and a few control flow statements to set the placeholders in the array to be minimum OR maximum values. You then just change the dateDiff() and strComp() lines to look for inverse integers (greater than zero instead of less than, and vise versa), depending on the direction parameter. And there you will have it, one awesomely complete array sorter.
Most people ask me for the code all in one piece, because they don't like gathering bits and pieces between explanations, so here's the code for the function all in one piece:
'==============================================
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
For d = c + 1 To uBound( arToSort, 2 )
if not compareDates then
if strComp( arToSort( sortBy, d ), smallestValue ) < 0 Then
smallestValue = arToSort( sortBy, d )
smallestIndex = d
End if
else
if not isDate( smallestValue ) then
arraySort = arraySort( arToSort, sortBy, false)
exit function
else
if dateDiff( "d", arToSort( sortBy, d ), smallestValue ) > 0 Then
smallestValue = arToSort( sortBy, d )
smallestIndex = d
End if
end if
end if
Next
if smallestIndex <> c Then 'swap
For e = 0 To uBound( arToSort, 1 )
tempValue = arToSort( e, smallestIndex )
arToSort( e, smallestIndex ) = arToSort( e, c )
arToSort( e, c ) = tempValue
Next
End if
Next
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |