0
<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?

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

Comments

1

Change:

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

to:

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

FIDDLE

Comments

1

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/

3 Comments

You have duplicate test2 row.
@Barmar Thanks I misunderstood the question
Your fiddle still isn't working. Change :first to :first-child. You're only selecting the first TD in the table, not the first TD on each row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.