1

I have a table in my HTML,

<table>
        <tr><td>1</td><td>2</td><td>3</td></tr>
        <tr><td>a</td><td>2</td><td>c</td></tr>
        <tr><td>x</td><td>2</td><td>3</td></tr>
        <tr><td>1</td><td>2</td><td>3</td></tr>
    </table>

And i wanted to find duplicate contents in the first and the second <td> elements contents.

This is what i got so far:

$(function() {
        $("table tr").each(function() {

        });
    });

I m stuck on selecting the first and the second element and comparing them. Do i just add a class or use jquery selector?

4
  • What do you want to do when you find dupes? And I'm assuming that you mean duplicate values in the same column between rows. Commented Oct 31, 2015 at 19:14
  • yes exactly and remove the duplicates Commented Oct 31, 2015 at 19:21
  • So in your example, the last row, first column should be cleared, and every second column except the first (containing a 2) should be cleared? Commented Oct 31, 2015 at 19:22
  • So basically in my example the first and the last row would be cleared -they both have the same <td> element in the first and the second column.(These are the only columns i wanted to compare for same values) Commented Oct 31, 2015 at 19:31

2 Answers 2

3

This is how you find the duplicates in a column, if I understood.

You can use instead of .addClass, .remove() if you want to remove it.

http://jsbin.com/wenuwewide/edit?js,console,output

  $('tr').each(function() {

      $(this).find('td').each(function(i) {

        if(values[i].indexOf($(this).text()) > -1) {
          $(this).addClass('duplicate');
        }

        values[i].push($(this).text());          
      });

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

Comments

2

just store the combination of the first two values as properties in an object

$(function() {
   var el = {};
   $("table tr").each(function() {
        // get row
        var row = $(this);
        // get first and second td
        var first = row.find('td:first-child').val();
        var second = row.find('td:nth-child(2)').val();
        // if exists, remove the tr
        if(el[first + second]) {
            $(this).remove())
        }
        else {
            // if it does not exist, add it with some random val
            el[first + second] = 1;
        }
   });
});

Comments

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.