Binary File, Array Scripting Secrets - Removing an array element
(Page 3 of 4 )
Removing an Array Element
Admittedly, VBScript does not provide very good support for arrays when compared to some other scripting languages. It provides the basic array functions but seems to lack any real method of performing advanced manipulation on an array. Therefore, when the need arises, we’re stuck with having to write our own functions. This function is one I wrote in response to the question “how can I remove elements from an array?”
arrTest = Array()
ReDim arrTest(2)
arrTest(0) = "Item 1"
arrTest(1) = "Item 2"
arrTest(2) = "Item 3"
Delete arrTest, 1
Let’s assume we have an array that looks like the example above. VBS doesn’t provide any way to remove an element from that array. To do that, I’ve written a Delete routine that accepts two parameters. The first is the array to work with and the second is the index of the element to remove.
Sub Delete(ByRef arrArray, intIndex)
For i = intIndex To UBound(arrArray) - 1
arrArray(i) = arrArray(i + 1)
Next
ReDim Preserve arrArray(UBound(arrArray) - 1)
End Sub
The routine itself is not complicated; it’s going to loop through each item in an array and rewrite it to a new position.
If you think about it, when you remove an array item, each item after that element will be moved to the next index down, replacing the element that was removed. The array size is then shortened to remove the duplicate item that ends up at the end. That’s exactly what this function will do.
By starting the For loop at the index position of the element to be removed, we can overwrite that element with the contents of the one that follows it. The loop then steps through each remaining element in the array, doing the same thing. Finally, the ReDim statement is used to remove one element from the array, leaving only those that we wanted.
Next: Adding Voice to Your Scripts >>
More Code Examples Articles
More By Nilpo