Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of table1 is the same as that in table2. For example:

Table1:

<Table>
    <tr>
        <td>123</td>
        <td>321</td>
    </tr>
    <tr>
        <td>545</td>
        <td>345</td>
    </tr>
    <tr>
        <td>0</td>
        <td>312</td>
    </tr>
    <tr>
        <td>123</td>
        <td>323331</td> 
    </tr>
</Table>

Second table:

<table>
    <tr>
        <td>545</td>
        <td>345</td>
    </tr>
    <tr>
        <td>545</td>
        <td>3122</td>
    </tr>
    <tr>
        <td>123</td>
        <td>321</td>
    </tr>
</table>

The expected result is:

123 321 - match found, do nothing 545 345 - match found, do nothing 545 3122 - no match found in table1 <-

This is the current approach being taken...

$('#runCheck').click(function(){
        var firstTable = $('#firstDiv table tr');
        var secondTable = $('#secDiv table tr');

        $(secondTable).each(function(index){
            var $row = $(this);
            var secTableCellZero = $row.find('td')[0].innerHTML;
            var secTableCellOne = $row.find('td')[1].innerHTML;

            $(firstTable).each(function(indexT){


                if ($(this).find('td')[0].innerHTML === secTableCellZero){
                    if ($(this).find('td')[1].innerHTML !== secTableCellOne){
                        $('#thirdDiv').append("first: " + secTableCellZero + " second: " + secTableCellOne+"<br>");

                    }

                }

            });

        });
     });  

Where might I be going wrong?

To reiterate once more:

2nd table states : row1 - john|likesCookies row2 - peter|likesOranges

1st table states : row1 - john|likesNothing row2 - john|likesCookies row3 - steward|likesToTalk row4 - peter|likesApples

expected output: john - value good peter - value not a match.

similar to VLOOKUP in excel

Answer №1

Take a look at this functional demo : here

I have developed two arrays to hold string values from each row in tables 1 and 2. Then, I compare these arrays to determine if each value in array1 has a corresponding match in array 2 using a flag variable.


Code Snippet :

$(document).ready(function() {
  var table_one = [];
  var table_two = [];
  $("#one tr").each(function() {
    var temp_string = "";
    count = 1;
    $(this).find("td").each(function() {
      if (count == 2) {
        temp_string += "/";
      }
      temp_string = temp_string + $(this).text();
      count++;
    });
    table_one.push(temp_string);
  });
  $("#two tr").each(function() {
    var temp_string = "";
    count = 1;
    $(this).find("td").each(function() {
      if (count == 2) {
        temp_string += "/";
        temp_string = temp_string + $(this).text();
      } else {
        temp_string = temp_string + $(this).text();
      }
      count++;
    });
    table_two.push(temp_string);
  });
  var message = "";
  for (i = 0; i < table_two.length; i++) {
    var flag = 0;
    var temp = 0;
    table_two_entry = table_two[i].split("/");
    table_two_cell_one = table_two_entry[0];
    table_two_cell_two = table_two_entry[1];
    for (j = 0; j < table_one.length; j++) {
      table_one_entry = table_one[j].split("/");
      table_one_cell_one = table_one_entry[0];
      table_one_cell_two = table_one_entry[1];
      console.log("1)" + table_one_cell_one + ":" + table_one_cell_two);
      if (table_two_cell_one == table_one_cell_one) {
        flag++;
        if (table_one_cell_two == table_two_cell_two) {
          flag++;
          break;
        } else {
          temp = table_one_cell_two;
        }
      } else {}
    }
    if (flag == 2) {
      message += table_two_cell_one + " " + table_two_cell_two + " found in first table<br>";
    } else if (flag == 1) {
      message += table_two_cell_one + " bad - first table has " + temp + "<br>";
    } else if (flag == 0) {
      message += table_two_cell_one + " not found in first table<br>";
    }
  }
  $('#message').html(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="one">
  <tr>
    <td>123</td>
    <td>321</td>
  </tr>
  <tr>
    <td>545</td>
    <td>345</td>
  </tr>
  <tr>
    <td>0</td>
    <td>312</td>
  </tr>
  <tr>
    <td>123</td>
    <td>323331</td>
  </tr>
</table>
<hr>
<table id="two">
  <tr>
    <td>545</td>
    <td>345</td>
  </tr>
  <tr>
    <td>545</td>
    <td>3122</td>
  </tr>
  <tr>
    <td>123</td>
    <td>321</td>
  </tr>
</table>
<hr>
<div id="message">
</div>
</div>

Answer №2

To simplify the process, you may want to consider approaching it by first converting the data in the initial table into string format, such as 123/321, 545/345, and so on.

Then, compare this modified list with the information in the second table. By eliminating any duplicate rows between the two tables, you will be left with the unique couples that do not have a match.

Answer №3

When optimizing for efficiency, consider looping through the first table only once to create an object with keys as the first cell values and arrays of second cell values. This eliminates the need to loop through the table multiple times, simplifying the lookup process.

Additionally, handling unmatched values can be a consideration when implementing this logic.

const firstTable = $('#firstDiv table tr');
const secondTable = $('#secDiv table tr');

const firstTableData = {};
firstTable.each(function() {
  const $tds = $(this).find('td');
  const firstCellData = $tds.eq(0).html().trim();
  const secondCellData = $tds.eq(1).html().trim();

  if (!Array.isArray(firstTableData[firstCellData])) {
    firstTableData[firstCellData] = [];
  }
  firstTableData[firstCellData].push(secondCellData);
})

$(secondTable).each(function(index) {
  const $tds = $(this).find('td');
  const secTableCellZero = $tds.eq(0).html().trim();
  const secTableCellOne = $tds.eq(1).html().trim();

  if (!firstTableData.hasOwnProperty(secTableCellZero)) {
    console.log('No match for first cell');
  } else if (firstTableData[secTableCellZero].indexOf(secTableCellOne) === -1) {
     console.log('No match for second cell');
  }
});

Consider the scenario where no matches are found to determine the appropriate course of action.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

option for uploading various data to the database using (php, ajax)

I am using a foreach loop to display data from the database on the screen. However, when I click the button, I do not see any results. Can someone please help me identify where I may be making mistakes? <table class="table"> <thead class="the ...

Using jQuery to gradually decrease the opacity of a variable

I'm attempting to fadeOut a variable that includes the classes I provided: var elementsToFadeOut = "'.slider-bg , .inner-content , .about-app , .contact-us'" $('.menu-li.a').click(function() { $(elementsToFadeOut).fadeOut(300) ...

Tips for safely storing JWT tokens in a react/next.js app:

After a valid user login following proper registration through REST API, I am looking for the best way to store the JWT token that is generated. I have researched various methods of storing JWT on the client side, including local storage, session storage, ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Simple Steps for Making a Get Request using Vuex in Vue.js

I'm trying to figure out how to store products in Vuex within my index component. import Vue from 'vue' import Vuex from 'vuex' import cart from "./modules/cart"; import createPersistedState from "vuex-persistedstate ...

What is the definition of the term "WebapiError"?

I'm currently developing a Spotify Web App that focuses on retrieving the top albums of KD Rusha using the Client ID and Artist ID to exclusively fetch his releases on Spotify. To accomplish this, I am utilizing an npm package called spotify-web-api-n ...

Is my rtk slice's initial state not being saved correctly in the store?

Currently diving into the world of RTK with typescript. I have created 2 slices - one using RTK query to fetch data (called apiSlice.ts) and another utilizing createSlice for handling synchronous state changes in my todo app (named snackbarSlice.ts). The ...

The asp.net code behind is reporting an undefined response text

var xhr = $.ajax({ type: 'GET', cache: false, url: 'loc.aspx?count=' + str, dataType: 'json', contentType: "application/json; charset=utf-8", async: false ...

Javascript Snake: I am having trouble making my snake's tail grow longer

I've created a snake game that is almost fully functional. The issue I'm facing is that when the snake eats food, the food changes location but the tail of the snake doesn't grow in size. I suspect that my understanding of arrays might be la ...

"Troubleshooting Issue: jQuery dataTables Filter Functionality Inoperative When Conjoined with

Incorporating the dataTables plugin and recycling code from another page to create a select for filtering a specific column, I encountered issues with the filtering functionality not working as expected. This was perplexing since it was code that had previ ...

Creating a basic popup with jQuery: A step-by-step guide

Currently in the process of creating a webpage. Wondering how to create a popup window with an email label and text box when clicking on the mail div? ...

Having an issue with retrieving value from a textfield in JavaScript

<input id="checkOldPassword" type="button" title="Check New Password" value="Check New Password" onclick="checkPassword()" /> <input id="newPassword" type="text" maxlength="8" min="8" /> <script language="javascript"> function checkPassw ...

What is the process for removing a document attribute in Sanity iO?

I have a collection of objects within my Sanity Document named Images which includes Comments An example comment object in the comments array looks like: { "_key": "6510dc79cf8b", "comment": "Hello world" ...

Implementing Multiple HTML Files Loading in QUnit

Currently, I am utilizing QUnit for unit testing JavaScript and jQuery. The structure of my HTML document is as follows: <!DOCTYPE html> <html> <head> <title>QUnit Test Suite</title> <script src="../lib/jquery.js">< ...

What causes jquery to not trigger PHP when the HTML file resides in a different location?

In my project structure, I have a 'js' folder containing the jQuery function and a PHP script. The HTML file is located in a separate folder. Currently, the setup looks like this: /server/js/global.js /server/js/script.php /server/html/stude ...

Steps for automatically playing the next song when a button is clicked

I have encountered a challenge in developing a music player. The issue lies in the loading of the next song when the user clicks the 'next' button. While the new data is successfully updated in both the state and render, the music does not automa ...

Ways to present a pop-up dialog box featuring word corrections

I have developed a word correction extension that encloses the incorrect word in a span element. Upon hovering over the word, a drop-down menu with possible corrections should be displayed. However, my current code is not functioning properly. How can I en ...

Leveraging colons in the process of object destructuring

I'm still trying to wrap my head around all the wonders of ES6. Ran across this snippet in an online article and I'm puzzled by how PrivateRoute is deconstructing the input props. What exactly is the purpose of component: Component here? const P ...

Leveraging IE conditional comments for including CSS or JavaScript files can lead to an increase in the number of HTTP

Our web designer has implemented special pages for Internet Explorer by using IE-specific comments. This means that certain stylesheets are only loaded if the user is using a specific version of IE: <!--[if lt IE 7]> <link type="text/css" rel="st ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...