Skip to content Skip to sidebar Skip to footer

Complex Table Merging Javascript & Jquery Algorithm

I have a rather unique problem that I'm having trouble solving. I have a 2 x 3 table, arranged like shown below.     _1____2__ 1-|____|____| 2-|____|____| 3-|____|____| Data

Solution 1:

Like this? http://jsfiddle.net/4zGvg/ Works with arbitrary rows/cols.

The idea: we have values matrix and span matrix. The values of span are

0 = hide this cell

1 = normal cell

x > 1 = cell with rowspan x

Iterate by columns in direct order and by rows in reverse order. If some cell's value is equal to the value below it, increase this cell's span and delete the span of the below cell:

for (var col = 0; col < cols; col++) {
    for (var row = rows - 2; row >= 0; row--) {
        if (values[row][col] == values[row + 1][col]) {
            span[row][col] = span[row + 1][col] + 1;
            span[row + 1][col] = 0;
        }
    }
}

Once this is done, you can use span to generate the complete table or to show/hide cells and set their rowspan attributes.

Solution 2:

Since it's always 2x3, you could just bruteforce it.

http://jsfiddle.net/Csxbf/

var $cells = $("td");

if ($cells.eq(0).text() == $cells.eq(2).text()) {

    if ($cells.eq(2).text() == $cells.eq(4).text()) {
        $cells.eq(2).hide();
        $cells.eq(4).hide();
        $cells.eq(0).attr("rowspan",3);
    } else {
        $cells.eq(2).hide();
        $cells.eq(0).attr("rowspan",2);
    }

} elseif ($cells.eq(2).text() == $cells.eq(4).text()) {
    $cells.eq(4).hide();
    $cells.eq(2).attr("rowspan",2);
}

This could definitely be optimized, this is just quick and dirty. You definitely would want to save references to the cells and not call eq so many times. You would have to do the same for the 2nd column.

If the table could change sizes, you would want to loop over each cell in the column and for every range that matched, hide the matches and set the rowspan. Relatively easy, but not really needed here.

Post a Comment for "Complex Table Merging Javascript & Jquery Algorithm"