TenVolt
                          Tech Notes
ASP > Arrays articles:

  Dumping the contents of a 2-dimensional array  Read
 • Sorting a multi-dimensional array in ASP VBScript
  Splitting delimited text into a multi-dimensional array  Read

Return to index of articles

Sorting a multi-dimensional array in ASP VBScript

Category: ASP
Category: Arrays

Here are two functions which will sort a multi-dimensional array. The first sorts in ascending order, the second in descending. Just pass the array, which column to sort by (first column is 0), and true or false for whether the column you're sorting by is a date or date/time field.

'============================================== 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 arraySort = arToSort end function '============================================== function arraySortREV( 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 ' REVERSE ORDER < 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( "s", arToSort( sortBy, d ), smallestValue ) <= 0 Then ' REVERSE ORDER > 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 arraySort = arToSort end function

4/1/2008

 TuneVault
 Music & MP3's
 10v Calendar
 Online & Easy
 Craigger
 Various & Misc.
 RetroVault
 Toys Toys Toys!
   

All contents ©2003 Ten Volt Consulting. All rights reserved.
Unauthorized duplication or use is a violation of applicable laws.
Webmaster Contact