Reputation: 1
<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
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();
}
});
});
Upvotes: 2
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