Comparing 2 lists/Tables in Javascript using Jquery -
i have 2 tables, table 1 , table 2.
table 1 has 2 columns:
col b | col c row 11 | row 12 row 21 | row 22 row 31 | row 32
table 2 has 2 columns:
col b | col c row 21 | row 22 row 21 | row 01 row 11 | row 12
i want compare table 1 table 2 , few things; compare both tables , make sure missing values of table 1 added table 2 in same order.
expected result
col b | col c row 11 | row 12 row 21 | row 22 row 31 | row 32 row 21 | row 01
i tried implementing using foreach loop on both tables, assuming tables json structure i'm not sure if i'm doing right. best way achieve above results? thanks
sample list:
{ "defaultvalue": [{ "cellvalues": [{ "defaultvalue": "row 11" }, { "defaultvalue": "row 12" }] }, { "cellvalues": [{ "defaultvalue": "row 21" }, { "defaultvalue": "row 22" }] },{ "cellvalues": [{ "defaultvalue": "row 31" }, { "defaultvalue": "row 32" }] }] } $.each(table1, function (table1rowindex, table1rowvalue) { $.each(table1rowvalue.cells)(), function (table1cellindex, table1cellvalue) { $.each(table2, function (table2rowindex, table2row) { $.each(table2.cells(), function (table2cellindex, table2cell) { // } }); }); }); });
i think want 3 nested loops instead of 4. proper nested loops rows, when loop through columns table 1, corresponding column table 2 using index.
it's idea make clone of 1 of tables act output...changing array looping through can cause issues.
$(document).ready(function() { var t1 = { "defaultvalue": [ {"cellvalues": [ { "defaultvalue": "row 11" }, { "defaultvalue": "row 12" }] }, {"cellvalues": [ { "defaultvalue": "row 21" }, { "defaultvalue": "row 22" }] }, { "cellvalues": [ { "defaultvalue": "row 31" }, { "defaultvalue": "row 32" }] } ] }; var t2 = { "defaultvalue": [ {"cellvalues": [ { "defaultvalue": "row 21" }, { "defaultvalue": "row 22" }] }, {"cellvalues": [ { "defaultvalue": "row 21" }, { "defaultvalue": "row 01" }] }, { "cellvalues": [ { "defaultvalue": "row 11" }, { "defaultvalue": "row 12" }] } ] }; var out = json.parse(json.stringify(t1)); // clone t1 use output $.each(t2.defaultvalue, function(i2, r2) { var rowmatch = false; $.each(t1.defaultvalue, function(i1, r1) { var cellmatch = true; $.each(r1.cellvalues, function(j, c1) { var c2 = r2.cellvalues[j]; if(c1.defaultvalue!=c2.defaultvalue) { cellmatch = false; return false; } }); if(cellmatch) { rowmatch = true; return false; } }); if(!rowmatch) { // r1 not exist in t2, need add out.defaultvalue.push(r2); } }); log(json.stringify(out)); }); function log() { var s = ''; $.each(arguments, function() { s += " " + this; }); $('#out').append(s+"<br>"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id=out></div>
Comments
Post a Comment