1

I have two tables, I have been using this code to to remove duplicate data found here:

var seen = {};
$('a').each(function() {
    var txt = $(this).text();
    if (seen[txt])
        $(this).remove();
    else
        seen[txt] = true;
});

Works well the problem that I have is if I can't choose which duplicate field to be removed, for example if I have a layout like this, it will remove either the tbody with class="off" or the class without, the rows can be moved so can appear in any order:

<table>
    <tbody class="off">
        <tr>
            <td>somedata</td>
        </tr>
    
    </tbody>
    <tbody>
        <tr>
            <td>somedata</td>
        </tr>
    
    </tbody>
</table>

I wondered if anyone knew how to modify the code so that it remove the duplicate that always contained the class="off" or if anyone had any other techniques.

Thanks any help be appreciated.

Community
  • 1
  • 1
ninjamaster
  • 83
  • 1
  • 6

2 Answers2

2

Here's an adapted version of that code you can use:

var seen = {};
$('tbody').each(function() {
    var elmt = {txt: $(this).text(), ref: this};
    if (seen[elmt.txt]) {
        if ($(seen[elmt.txt].ref).hasClass('off')) {
            $(seen[elmt.txt].ref).remove(); seen[elmt.txt].ref = this;
        } else {
            $(this).remove();
        }
    }
    else
        seen[elmt.txt] = elmt;
});

Demo here.

It will search for all tbody with repeated text() content. If it finds a repeated one, it will preferrably remove the one with the off class. If none have got it, it will remove the last one found.

Examples:

The first tbody will prevail:
<table>
    <tbody class="blu"><tr><td>somedata</td></tr></tbody>
    <tbody class="off"><tr><td>somedata</td></tr></tbody>
    <tbody class="gre"><tr><td>somedata</td></tr></tbody>
</table>

The second tbody will prevail:
<table>
    <tbody class="off"><tr><td>somedata2</td></tr></tbody>
    <tbody class="gre"><tr><td>somedata2</td></tr></tbody>
    <tbody class="blu"><tr><td>somedata2</td></tr></tbody>
</table>
Community
  • 1
  • 1
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

Working jsFiddle Demo

As you wrote:

I wondered if anyone knew how to modify the code so that it remove the duplicate that always contained the class="off".

Just get the .off classes and remove them:

$('tbody.off').remove();

CSS

Also, there is no need to use jQuery. You can hide duplicate items with css:

tbody.off { display: none; }