user2269603
user2269603

Reputation: 1

Removing duplicate rows in html table based on a one column

<table id="test" border="1">
    <tr>
        <td>test1<td>
        <td>00.00.00<td>
    </tr> 
    <tr>
        <td>test2<td>
        <td>00.00.00<td>
    </tr>
    <tr>
        <td>test1<td>
        <td>00.00.01<td>
    </tr>
    <tr>
        <td>test2<td>
        <td>00.00.01<td>
    </tr> 
</table>


<script type="text/javascript" >
var seen = {};
    $('table tr ').each(function() {
       var txt = $(this).text();
       if (seen[txt]) $(this).remove();
       else seen[txt] = true;
    });
</script>

I tried it with the above jquery script but it fails for this scenario. I would like to remove duplicates only based on the first column. any suggestions on this, please?

Upvotes: 0

Views: 9410

Answers (3)

msapkal
msapkal

Reputation: 8346

var arr = $("#test tr");

$.each(arr, function(i, item) {
    var currIndex = $("#test tr").eq(i);
    var matchText = currIndex.children("td").first().text();
    $(this).nextAll().each(function(i, inItem) {
        if(matchText===$(this).children("td").first().text()) {
            $(this).remove();
        }
    });
});

DEMO

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

Use the map() function to create an array of objects containing the value and the element. Iterate through this array comparing each value to other values in the array, removing the tr elements when duplicates are encountered.

It should also be noted that the html has several unclosed td tags

Javascript

var values = $("#test tr td:first").map(function(){
    return {e: this, val: $(this).html()};
});

$.each(values, function(i,e){
    $.each(values,function(ind,el){
        if(el.val == e.val){
           $(el.e).parents("tr").remove();
        }
    });
});

HTML

<table id="test" border="1">
<tr>
    <td>test1</td>
    <td>00.00.00</td>
</tr> 
<tr>
    <td>test2</td>
    <td>00.00.00</td>
</tr>
<tr>
    <td>test1</td>
    <td>00.00.01</td>
</tr>
<tr>
    <td>test2</td>
    <td>00.00.01</td>
</tr> 
</table>

Working Example http://jsfiddle.net/p72BB/3/

Upvotes: 1

Barmar
Barmar

Reputation: 780974

Change:

var txt = $(this).text();

to:

var txt = $("td:first-child", $(this)).text();

FIDDLE

Upvotes: 1

Related Questions