Creating Useful Array Functions
(Page 1 of 5 )
Visual Basic Scripting Edition doesn’t provide very good support for working with arrays. It has a very limited number of array functions, especially when compared to similar languages like JavaScript. In this article, I’m going to show you some custom functions you can add to your scripts that will give you the flexibility you might find in other languages.
Pop and Push
Many languages feature the Pop function, which is used to remove the last element from an array. The function returns the contents of the removed element.
Function Pop(ByRef arrArray)
' Remove and return the last element of an array.
If UBound(arrArray) = 0 Then Pop = vbNull : Exit Function
Pop = arrArray(UBound(arrArray))
ReDim Preserve arrArray(UBound(arrArray) - 1)
End Function
Here you can see the Pop function. It requires a single parameter that is the array on which to act. Notice that I’m passing the array by reference (using the ByRef keyword). This forces the function to act on the original array and not a duplicated array.
The function begins by finding the upper boundary of the array. This provides the number of elements in the array. If this number is 0, then the array has only a single element and the function will exit without doing anything. In this instance, the function returns a Null value.
Suppose that the array does contain more than one element; the last element is read, and then the array is resized to be one element smaller than it started. Using the Preserve keyword, we ensure that the remaining array elements remain unchanged.
The Push function is the opposite of Pop. Rather than removing an element, it adds an element to the end of an array and returns a value indicating the new size of the array.
Function Push(ByRef arrArray, varElement)
' Add an element to the end of an array. Return new length.
ReDim arrArray(UBound(arrArray) + 1)
arrArray(UBound(arrArray)) = varElement
Push = UBound(arrArray)
End Function
You can see here that the structure of the Push function is very similar to the one you just saw in Pop. Here though, we begin by adding an element to the end of the array and assigning it the value from a passed parameter. We then grab the new length of the array with the Ubound function and return that value.
Next: Using Shift and Unshift >>
More Code Examples Articles
More By Nilpo