My goal is to merge rows for the first 3 columns of my table but if the first column has a different value, my second column should not merge.
To visualize better here is my current table:
And I want to make it look like this:
As you can see on the first image, BBB1 is merged 4x because it appeared on my query 4x, but since it has a different value on the first column, I need to merge it like it shows on the 2nd image.
Here’s my current code:
<script>
var table = document.getElementById('myTable');
function mergeCells(table, startIndex) {
let headerCell = null;
for (let row of table.rows) {
const firstCell = row.cells[startIndex];
if (headerCell === null || firstCell.innerText !== headerCell.innerText) {
headerCell = firstCell;
} else {
headerCell.rowSpan++;
firstCell.remove();
}
}
}
mergeCells(table, 2);
mergeCells(table, 1);
mergeCells(table, 0);
</script>
2
Answers
I changed condition to concatenate current column text and previous column text, and compare with next row like "AAA1BBB1" === "AAA2BBB1".
I think make more simply using jquery.
You can merge cells in one column only if the corresponding cells in all previous columns have also been merged. The following code works recursively: after mergeable cells from row M to row N in one column have been determined, it invokes itself to process the cells in these rows in the next column and only then merges the mergeable cells.