Unfortunately, I'm not able to offer code this week (responding from phone) but...
Assuming the filtering question is on a previous page, the solution would be to, as you insert the headers, test for visibility of the following row and add a CSS display style accordingly.
Assuming the filtering question is on a previous page, the solution would be to, as you insert the headers, test for visibility of the following row and add a CSS display style accordingly.