1

I have the following table that outputs values from db via a loop and looks something like this:

<table class="myData">
<tr>
    <td class="lbl">
    Item 1:
    </td>
    <td>
    Amateur Team
    </td>

</tr>

<tr>
    <td class="lbl">
    Item 2:
    </td>
    <td>
    New School
    </td>
</tr>
...
<tr>
    <td class="lbl">
    Item 53:
    </td>
    <td>
    New School
    </td>
</tr>
</table>

I would like to use jQuery to highlight duplicate values in the second column, perhaps by changing color. Can that be done?

if (duplicate(s)) { 
    $(".myData td:nth-child("2").css("color","red");
}
santa
  • 12,234
  • 49
  • 155
  • 255

2 Answers2

3

You can do something like this. Refer to this answer for an explanation on seen

var seen = {};
$('.myData td:nth-child(2)').each(function() {
    var txt = $(this).text();
    if (seen[txt])
        $(this).css('color','red');
    else
        seen[txt] = true;
});

Sorry, I just realised this wouldn't highlight the first occurrence. I will fix it up when I get home later tonight if someone else hasn't already answered.

Community
  • 1
  • 1
Kurt
  • 7,102
  • 2
  • 19
  • 16
  • Very elegant solution @Prowla! My implementation was on the same lines as @icyrockcom, but I discarded when I saw yours! – bPratik Mar 07 '12 at 04:39
  • Actually this works great for me. I mark only duplicates for removal. Thanks! – santa Mar 07 '12 at 17:17
1

You can do something like this:

Make a map of duplicate count

var vals = {};
$(".myData td:nth-child(2)").each(function(i, e) {
    var txt = $(e).text();
    var val = vals[txt];
    vals[txt] = val == null ? 1 : val + 1;
})   

Mark duplicates

$(".myData td:nth-child(2)").each(function(i, e) {
    var txt = $(e).text();
    if(vals[txt] > 1) {
        $(e).css("color","red");
    }
})    

Live example:

icyrock.com
  • 27,952
  • 4
  • 66
  • 85