Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript were forced to write their own sort routines, be that a bubble sort, a heap sort, a quicksort, or some other type of sorting algorithm.
But that was before the advent of the .NET Framework. If you have the .NET Framework installed on your computer then you can sort an array using code no more complicated than this:
In this script we start off by creating an instance of the System.Collections.ArrayList object, with System.Collections.ArrayList being a .NET class used for creating dynamic arrays. After creating our arraylist object we then use the Add method to add all the items to the array:
Once we’ve populated the arraylist we can then sort the data simply by calling the Sort method:
After that all we have to do is set up a For Each loop and echo back the values within the array:
Needless to say, that’s way easier than writing your own bubble sort routine. Just remember to create an arraylist object (not a regular VBScript array), and to add items to that arraylist one at a time. Do that, and you’ll be able to sort string arrays with the best of them.
As for sorting items in descending order, well, to be honest, we couldn’t find a straightforward method for doing that (at least not without creating and using yet another .NET object). Therefore, we came up with a simple little workaround instead: