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

Common reasons why you may encounter the error "Uncaught TypeError: $(...).DataTable is not a function"

I recently started working with DataTable.js, and when I tried to integrate it into my ASP.NET Core MVC 5.0 project, I encountered an error: Uncaught TypeError: $(...).DataTable is not a function After doing some research on Google, I discovered that this ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

How do I ensure my object is fully constructed before sending it in the response using NodeJS Express?

Currently, I am in the process of constructing a result_arr made up of location objects to be sent as a response. However, my dilemma lies in figuring out how to send the response only after the entire array has been fully constructed. As it stands, the re ...

Tips on Initiating a Phone Call using a Button Click within a Recyclerview

When using the method ACTION_CALL, I encountered a problem. Clicking the button on the first card view causes the app to call the phone number 11111111. However, clicking the button on the second card view also calls the same number 1111111. What I want i ...

Execute the JavaScript callback

I am encountering an issue when trying to pass an anonymous function as a callback and call it. I seem to be missing something simple, because I keep getting the error 'Uncaught type error - callback is not a function'. Here is what I am attempti ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

Navigate to a specific URL path and send properties as arguments in the function for handling events

I am working on a vuetify autocomplete search feature. When a user selects an item, I need to navigate to a specific route and pass some props along. However, my attempts to change the current route without passing props have resulted in errors. Here is w ...

Retrieve JSON data by making a POST request to a website's API

Can you help me retrieve Json data from a website API using JavaScript? I'm trying to fetch quotes from the following website: for my quotes generator page. While I have some understanding of making GET requests, it seems that this API requires POST ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

How can I add a comma after every third number in a react component?

I am currently developing an input feature where I need to insert a comma after every 3 numbers, such as (352,353,353). The challenge is to display this format in a text field. Since I am new to working with React, I would appreciate any guidance on how to ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

s3 is having trouble uploading the file and is returning an error stating SignatureDoesNotMatch

I'm experiencing an issue while attempting to upload images to my s3 bucket in aws. The error message SignatureDoesNotMatch keeps appearing. Below is the code I am using to upload the file/image: FrontEnd const file = e.target.files[0]; const fileP ...

Monitoring variables in different AngularJS controllers

I have a component named histogram demo which includes a distinct controller with a variable known as $scope.selectedElements. I aim to monitor this variable in the primary appCtrl controller. How can I achieve access to this variable without using $rootSc ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

Can you identify the issue in this code?

I am facing an issue with using this code to save values in a table when the page loads. The function that searches for values is written in PHP, and I need to use these values in my script. Unfortunately, the current approach I am trying doesn’t seem ...

Guide on seamlessly adding NPM "dependencies" to index.html using <script> tags in a VUE JS WEBPACK project

Are there any tools available that automatically inject or include NPM dependencies into the index.html file, similar to the GRUNT-BOWER plugin for BOWER dependencies? The project in question is a VUE-CLI WEBPACK project. Can this functionality be achieve ...

The "initialized" event in angular2-tree-component fires prior to the data being loaded

Utilizing the angular2-tree-component, my goal is to display an already expanded tree. According to Angular docs, the initialized event should be used for expanding the tree after the data has been received: This event triggers after the tree model has ...

Troubleshooting: Unable to delete data using $http in AngularJS

When using the $http service in Angular JS to call an API for deleting a message, I am receiving a successful response but the value is not actually being deleted. Interestingly, when I directly access the same API in my browser, the message gets deleted s ...

res.render() Displaying Data in Frontend using Local Variables

I have a question regarding defining local variables in Express. When I use res.render(view, {variable: variable}), how can these variables be accessed on the frontend? Where are they stored? I attempted to access a variable with console.log(variable), but ...

After a period of time since the server has been initialized, the function req.isAuthenticated() no

In my Node.js routes.js file, I have a function implemented to check if a request is isAuthenticated before serving it: function isLoggedIn(req, res, next) { if (req.isAuthenticated()) { console.log('Session Expiry '+req.session.cook ...