How to merge rows that have the same values on my dynamic table with some conditions using JavaScript

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:

https://imgur.com/uGcr54O

And I want to make it look like this:

https://imgur.com/8ibuvoU

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) {
              var headerCell = null;

                for (var row of table.rows) {
                var firstCell = row.cells[startIndex];

                if (headerCell === null || firstCell.innerText !== headerCell.innerText) {
                  headerCell = firstCell;
 
                } else {
                  headerCell.rowSpan++;
                  firstCell.parentElement.removeChild(firstCell);
                
                }
              }
            }
              mergeCells(table, 2);
              mergeCells(table, 1);
              mergeCells(table, 0);
 </script>