Search code examples
jqueryhtmlhtml-tableduplicatescell

Remove duplicated table column incl. table head to new table


I've tried different workarounds and modified some scripts but I can't do it in the way I'd like to

I've a table and all duplicated columns (inclusive the additional table th) should be moved to an table 2 ... only the different columns should be stay in table 1

<table width="200" border="1">
<tbody>
<tr>
  <th scope="col">Colour</th>
  <th scope="col">Weight</th>
  <th scope="col">Width</th>
  <th scope="col">Size</th>
  <th scope="col">Price</th>
</tr>
<tr>
  <td>black</td>
  <td>20kg</td>
  <td>10cm</td>
  <td>XL</td>
  <td>20,90€</td>
</tr>
<tr>
  <td>green</td>
  <td>20kg</td>
  <td>8cm</td>
  <td>XL</td>
  <td>20,90€</td>
</tr>
<tr>
  <td>red</td>
  <td>20kg</td>
  <td>5cm</td>
  <td>XL</td>
  <td>10,00€</td>
</tr>
 </tbody>
</table>

Any snippet or possible workaround?


Solution

  • Here a snippet to get started

    $("table tbody tr").each(function (index, option)
                {
                    var FirstColumnVal = $(this)[0].cells[0].innerText;
                    var SecondColumnVal = $(this)[0].cells[1].innerText;
                    $("table tbody tr").each(function (index1, option1)
                    {
                        // Avoid same column comparision    
                        if(index != index1)
                        {
                            // 1st Column Check
                            if ($(this)[0].cells[0].innerText == FirstColumnVal)
                            {
                                // duplicate found - remove element or move to other table
                            }
    
                            // 2nd Column Check 
                            if ($(this)[0].cells[1].innerText == SecondColumnVal) {
                                // duplicate found - remove element or move to other table
    
                            }
                        }
                    });
                });
    

    Do the same for other columns.