/ Published in: ASP

This function returns the array with all instances of the specified value removed
Expand |
Embed | Plain Text
'This function returns a copy of the array with all instances of the specified value removed function removeValueFromArray(byval arrayName, valueToRemove) amountFound = 0 'keeps track of how many it found so that it knows what size to redim the array at the end topIndex = ubound(arrayName) 'hold the value of the ubound in a variable so that you can decrement it when you find the value to remove for i = 0 to ubound(arrayName) if i > topIndex then 'this keeps the loop from checking past the topIndex. keeps the loop from being infinite when the last value exit for ' exit the loop when you have reached the end of the checked values end if if arrayName(i) = valueToRemove then topIndex = topIndex - 1 'decrement the topIndex when you shift down so that it doesn't check the duplicated values at the end of the array amountFound = amountFound + 1 ' the value has been found so increment for j = i to (ubound(arrayName) - 1) 'shift the array values left to overwrite the value to remove arrayName(j) = arrayName(j + 1) next 'if the next element was equal to valueToRemove you have to go back and get rid of it too if arrayName(i) = valueToRemove then i = i - 1 ' this gets incremented at the beginning of the loop so don't worry about negative values end if end if next redim preserve arrayName(ubound(arrayName) - amountFound) removeValueFromArray = arrayName end function
Comments

You need to login to post a comment.
This code is wrong and in some cases takes to a neverending loop. Here's the corrected version:
function removeValueFromArray(byval arrayName, valueToRemove) amountFound = 0 'keep track of how many you found so that you know what size to redim array at the end for i = 0 to ubound(arrayName) if arrayName(i) = valueToRemove then amountFound = amountFound + 1 for j = i to (ubound(arrayName) - 1) 'shift array values left over value to remove arrayName(j) = arrayName(j + 1) next i = i - 1 '**** this has to be executes every time a value is found! end if next redim preserve arrayName(ubound(arrayName) - amountFound) removeValueFromArray = arrayName end function
To work correctly you have to remove line 11 and line 13 !!!!!!!!!!!!!!
And furthermore line 12 has to be: if i>0 then i=i-1
Sorry about that. It was going into an infinite loop when there was an instance of the value to remove at the end of the array. Because this function shifts values down and overwrites, it was copying the valueToRemove over the other positions in this array. It was, in a sense, smearing the valueToRemove down each time that it found an instance.
I changed this now so that it keeps track of which values have been smeared from the top and does not check those.