2

I have two tables. I want to delete unmatching rows. Compare with first column in Table1 and compare with first column in Table2.

Table1

111   aaa
222   bbb
333   ccc

Table2

333  xxx
444  zzz
111  vvv

result of Table2

333 xxx
111 vvv

I tried some thing here

Please help me these

Thank you.

1

3 Answers 3

1

Please check if this works for you - http://jsfiddle.net/ylokesh/m7v4tpnu/19/

HTML

<table id="T1">
    <tr><td>111</td><td>xxx</td></tr>
    <tr><td>222</td><td>www</td></tr>
    <tr><td>333</td><td>ttt</td></tr>
</table>

<table id="T2">
    <tr><td>444</td><td>www</td></tr>
    <tr><td>111</td><td>xxx</td></tr>
    <tr><td>333</td><td>ttt</td></tr>
</table>

JavaScript

$('#T1 tr').each(function(){
    var data = $(this).html();
    $('tr', '#T2').each(function(){
        if($(this).html()===data){
            $(this).remove();
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Check this solution (DEMO):

var newTbl = $('#newTbl');
$('#Table1 tr').each(function(){
    var that = $(this);
    var td = that.find('td').eq(0);
    var a = td.text();
    var arr = [];
    $('#Table2 tr').each(function() {
        var that = $(this);
        var b = that.find('td').eq(0).text();
        arr.push(b);
    }); 
    if ($.inArray(a, arr) != -1) {
        var c = $('#Table2').find('td:contains(' + a + ')').next().text();
        newTbl.append('<tr><td>' + a + '</td><td>' + c + '</td></tr>');
    }
});
  1. Get the text of the first cell of the first row of Table1 and store it to a variable (a)
  2. Loop through the second table and see if this variable matches with the text of any of the first cells of each row.
  3. If any match found, append a new row to newTbl table with this variable as text of the first cell.

Comments

0

Try this solution:

var notrem = [];
$('#Table1 tr').each(function(){
   var currentRowHTML = $(this).find("td:first").html();

    $('#Table2 tr').each(function(i){
        var c= $(this).find("td:first").html();
        if(c == currentRowHTML ){
            notrem.push(i);
         }
    });
});

$('#Table2 tr').each(function(i){
    if(notrem.indexOf(i) < 0){
        $(this).remove();
    }
});

Explanation:

First gather all indexes of Table2 that are equal and are not to be removed. Next iterate again and remove those that are not present innotrem array.

http://jsfiddle.net/ndru/m7v4tpnu/14/

Comments

Your Answer

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