Wednesday, 7 August 2013

Generate row grouping recursively in JavaScript

Generate row grouping recursively in JavaScript

I am having trouble with a function to generate a table with multiple
levels of row groupings in JavaScript.
The recursive function is called drawGrouping and it is defined as:
this.drawGrouping = function(tbody, listOfObjects, groupings, index) {
//check if there are grouping levels remaining
if (index < groupings.length) {
var g = groupings[index];
var pvList = database.getValuesForProperty(g);
for (var i = 0; i < pvList.length; i++) {
var val = pvList[i];
//creates a grouping <tr> row
var row = this.generateGroupingRow(g, val, index+1);
tbody.append(row);
//returns a filtered list of objects that belong under this
grouping
var objs = database.filter(listOfObjects, g, '==', val);
//call the function again, supplying the filtered list
//and a new index
this.drawGrouping(tbody, objs, groupings, index++);
}
} else {
//exits the recursion and prints the regular table rows
for (var i = 0; i < listOfObjects.length; i++) {
tbody.append(this.generateTableRow(listOfObjects[i]));
}
}
}
Then I kick off the function with:
this.drawGrouping(tableBodyTag, listOfObjects, listOfGroupNames, 0);
The problem is that the first level of grouping works fine, but subsequent
levels will only appear for the first section. I believe it is a problem
with variable scope but I am not sure.
Here is an image of what the output looks like with some junk data. The
table has been grouped by 'Owner First Name' and then by 'Fiscal Period'
and for some reason the latter grouping only appears one time.
What am I missing?

No comments:

Post a Comment