4

I'm trying to filter a two-dimensional array with VBScript but VBScript's built-in "filter" function only works with single dimensional arrays. I'm using an array of "rs.GetRows()", so is there a simple function that works with two-dimensional arrays?

EDIT: It's not about filtering database records, it's about filtering multidimensional arrays. I know I can filter those records at database level, but that's not what I want. So what I'm looking for is a filter function for multidimensional arrays.

3
  • ADO recordsets have a filter property themselves. could you filter the recordset before returning the rows? Commented Feb 16, 2011 at 9:07
  • Can't you perform the filter on the database itself? What can be done on the server, should be done on the server. Commented Feb 16, 2011 at 9:53
  • I'm already filtering the database records but I will process that two-dimensional array with another array. I have two queries that are too complicated to be joined, so I need a multidimensional array filter function. Commented Feb 16, 2011 at 13:22

2 Answers 2

3
Option explicit

' actual function
Public function filter2dArray(a, text)
    Dim i
    For i = ubound(a) to lbound(a) step -1
        If instr(join(a(i), vbTab), text) = 0 Then
            ' no match. switch it with ubound and delete ubound
            a(i) = a(ubound(a))
            ReDim preserve a(ubound(a)-1)
        End If
    Next
    filter2dArray = a
End Function

' test code
Dim b, i
b = array(    array("row1", "monday", "work"), _ 
            array("row2", "tuesday", "work"), _
            array("row3", "wednesday", "free"))

b = filter2dArray(b, "work")

For i = lbound(b) to ubound(b)
    msgbox i & ": " & join(b(i), vbTab)
Next

As you requested: A filter function for 2D arrays.
Limitations: it only works on textual 2d arrays and it does not have the Include and Compare switch, but that is not difficult to achieve.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I am kind of new to VBScript like I have a very very old project and I have to maintain it for now but does that function even work because it keeps giving me subscript out of range error
0

If the requirement is you don't change your interim data structure, then looping through the array and discarding elements that don't fit your filter criteria, or adding elements to a new array seems a good bet. I guess the number of records you're dealing with will have a big bearing on if you choose this approach.

An alternative could be to load your subset into an interim table, then do the filter on that. Some code / indication of the data might help inform the best approach.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.