Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array:

  tableData(0) = "1, Hans, Testperson, Munich, Germany"
  tableData(1) = "2, Petra, Testperson, Hamburg, Germany"

The idea is that the array index indicates the row the data came from, while the values on the right side represent the column values all wrapped up in a string and separated by ,.

As of now, my method looks like this:

function getTableData() {
   var tableRows = document.querySelectorAll("#tableId tr");
   var data = []
   for (var j = 1; j < tableRows.length; j++) {
      var rowColumns = tableRows [j].querySelectorAll("td")
      var columnData = ""
      for (var k = 1; k < rowColumns.length; k++) {
         columnData = columnData + rowColumns[k].innerText
         if (k < rowColumns.length-1) {columnData = columnData + ","}
      }
      data.push(columnData)
   }
 }

It's doing the job well, but when the table exceeds 1000 rows, it starts to slow down. Is there a more efficient way to achieve this using only pure JS?

Thank you in advance

Answer №1

Utilize the table element API to easily access rows and cells without the need for nested queries.

You can either use the map function to concatenate the cell inner texts:

const tableBody = document.getElementById('tableId');

const data = [];
for (const row of tableBody.rows) {
  data.push([...row.cells].map((c) => c.innerText).join(', '));
}

console.log(data);
<table id="tableId">
    <thead>
        <tr><td>id</td><td>first</td><td>last</td><td>city</td><td>country</td></tr>
    </thead>
    <tbody>
        <tr><td>1</td><td>Petra</td><td>Müller</td><td>Hamburg</td><td>Germany</td></tr>
        <tr><td>2</td><td>Hans</td><td>Schneider</td><td>Munich</td><td>Germany</td></tr>
        <tr><td>3</td><td>Jan</td><td>Meyer</td><td>Düsseldorf</td><td>Germany</td></tr>
        <tr><td>4</td><td>Tura</td><td>Fischer</td><td>Leipzig</td><td>Germany</td></tr>
    </tbody>
</table>

Alternatively, you can gather the cell inner texts into a single string:

const tableBody = document.getElementById('tableId');

const data = [];
for (const row of tableBody.rows) {
  let rowData = '';
  for (const cell of row.cells){
    rowData += `${cell.innerText}, `;
  }
  data.push(rowData.slice(0,-2));
}

console.log(data);
<table id="tableId">
    <thead>
        <tr><td>id</td><td>first</td><td>last</td><td>city</td><td>country</td></tr>
    </thead>
    <tbody>
        <tr><td>1</td><td>Petra</td><td>Müller</td><td>Hamburg</td><td>Germany</td></tr>
        <tr><td>2</td><td>Hans</td><td>Schneider</td><td>Munich</td><td>Germany</td></tr>
        <tr><td>3</td><td>Jan</td><td>Meyer</td><td>Düsseldorf</td><td>Germany</td></tr>
        <tr><td>4</td><td>Tura</td><td>Fischer</td><td>Leipzig</td><td>Germany</td></tr>
    </tbody>
</table>

Answer №2

To optimize the column loop in retrieving table data, it would be more efficient to utilize map and join methods instead of continuously adding to a string:

function fetchTableData() {
  var rows = document.querySelectorAll("#tableId tr");
  var data = [];
  for (var k = 1; k < rows.length; k++) {
    data.push([...rows[k].querySelectorAll("td")].map((item) => item.innerText).join(","));
  }
}

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

Leveraging the Google Geocode API through HTTP GET requests

I am facing a challenge in my HTML file where I have a map and I am using HTTP get with jQuery to retrieve a device's location. However, I am struggling to plot this location on the map. I need to parse the location information and display it accurate ...

No longer will popups be blocked

I've been trying to work with jQuery to create a popup. But I'm facing an issue where my code is being blocked by Google. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { var flag = true; ...

Hover and focus effects of the main navigation menu in Semantic UI CSS

I seem to be having trouble styling my navbar with semantic-ui. I want to make changes to the color and background-color on hover and when focused. However, no matter what I try, the hover effect just won't work. I was only able to achieve it using jQ ...

What is the process for creating an xpath for hyperlinks with the 'contains text' attribute?

I am in need of creating Xpath for links based on contained text. I have devised the following code to achieve this, however, a scenario arises when there are three links named 'Entity', 'Entity Type', and 'Entity Group'. If I ...

Creating arrays from an array list in PHP: A step-by-step guide

Is there a way to create arrays with the names of the values in another array as elements? $array_names = array("name1","name2","name3",...); For each item in $array_names, how can I generate an array with the name of that item? $name1, $name2, $name3 . ...

What is the best way to fetch a UniqueID using document.getElementById()?

I am looking to utilize the __doPostBack JavaScript function. __doPostBack(obj.UniqueID,''); The challenge I'm facing is that I only have the ClientID of my object - ctl00_cpholder_myObjId document.getElementById("ctl00_cpholder_myOb ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

Addressing an error of "call stack full" in nextjs

I am currently working on a project in nextjs where I need my billboard to continuously scroll to show different information. The Nextjs debugger keeps showing me an error message that says 'call stack full'. How can I resolve this issue? con ...

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

What is the best method for connecting my HTML to jQuery code?

Apologies for my lack of experience in coding, but I will try to keep this brief. To put it simply, when I insert my jQuery code directly into the HTML file below the content, it works perfectly - the element I want to animate 'hides' and then & ...

`Why won't the checkbox uncheck when the dropdown is changed in jQuery?`

I have a roster of users, each with a unique checkbox for selection. When I adjust the dropdown menu, a new group of users is chosen and marked as selected. However, I am struggling to uncheck the previously selected checkboxes based on the last dropdown c ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Comparing document.getElementById and the jQuery $() function

Is this: var contents = document.getElementById('contents'); The equivalent to this: var contents = $('#contents'); Considering that jQuery is present? ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

Utilizing Stripe for Payment Processing

I'm encountering a problem with getting Stripe charging to function properly. Despite having manually loaded Composer since it wouldn't install, I am not receiving any PHP errors and the token creation is running smoothly. There don't seem t ...

Why is the parameter value becoming null during an Ajax call?

I am passing a parameter from HTML to JSP, but when I try to retrieve the value in JSP, it returns null. Can someone help me figure out what's wrong with my code and provide any suggestions? The value is successfully displayed in an alert using JavaS ...

How to Retrieve Content from an iFrame Using jQuery?

I am facing a challenge with an HTML form that is directed to an IFRAME upon clicking "submit". The iframe then loads a page after the submission, which indicates whether the user-input data is valid or not. It simply displays on screen as "TRUE" or "FALSE ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...