Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate <tr>'s through jquery

Tags:

html

jquery

I have table which is bound dynamically:

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

I want to remove duplicate table rows, producing a result like this.

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

I'm trying to do it through this btnRearrange click.

 $('#btnRearrange').bind("click", function() {
   // want some help hear
 });

Thanks.

like image 949
4b0 Avatar asked Nov 22 '11 21:11

4b0


2 Answers

Try -

var seen = {};
$('table tr').each(function() {
  var txt = $(this).text();
  if (seen[txt])
    $(this).remove();
  else
    seen[txt] = true;
});
<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
      <td>
  </tr>
  <tr>
    <td>test2
      <td>
  </tr>
</table>

Code is taken (and very slightly changed) from this question - JQuery: Remove duplicate elements?

like image 109
ipr101 Avatar answered Nov 16 '22 22:11

ipr101


$('#btnRearrange').bind("click", function() {
    var contents = {}, text;
    $("#test td").each(function() {

        text = $(this).text();

        if( !( text in contents ) ) {
            contents[text] = true;
        }
        else {
            $( this.parentNode ).remove();
        }

    });
});

jsfiddle: http://jsfiddle.net/jKs4k/

like image 3
Esailija Avatar answered Nov 16 '22 22:11

Esailija