Billy Billy - 3 months ago 11
jQuery Question

How to remove rows that contain the same data within the <tr>

I have a table that produces data dynamically. i would like to know how to remove rows that contain the same data within

<tr>
elements and keep the first two
<tr>
elements. This question is very similar to this

<table id="test">
<tr>
<td>test1<td>
</tr>
<tr>
<td>test2<td>
</tr>
<tr>
<td>test1 a<td>
</tr>
<tr>
<td>test2 b<td>
</tr>
</table>


I would like the result to be:

<table id="test">
<tr>
<td>test1<td>
</tr>
<tr>
<td>test2<td>
</tr>
</table>

Answer

You can achieve this by looping through each td and then filtering out other td which start with the same string before removing them. Try this:

var $tds = $('#test td');
$tds.each(function() {
  var text = $(this).text();
  $tds.not(this).filter(function() {
    return $(this).text().indexOf(text) == 0;
  }).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="test">
  <tr>
    <td>test1<td>
  </tr>
  <tr>
    <td>test2</td>          
  </tr>
  <tr>
    <td>test1 a<td>
  </tr>
  <tr>
    <td>test2 b<td>
  </tr>
</table>