The ideal formats for tables and JavaScript: How to effectively retrieve arrays from a table?

Given the task of defining a function that extracts the mode of weights from an HTML table containing age and weight data for individuals within a specified age range. The function needs to be able to handle tables of any size. I am looking for the most effective way to filter rows based on age and then extract the corresponding weights into an array. While I initially considered using square bracket notation, it seems this is not applicable with HTML tables in JavaScript. Are there alternative methods similar to square bracket notation that can be used for HTML tables? My primary focus is understanding how to manipulate HTML tables efficiently in Javascript, rather than solving this specific problem.

function birthWeightByAge(ageWeightTbl, rowCount, minVal, maxVal) {
    var weightArray = [];
    //Iterate through each row in the table
    for (var i =0; i < rowCount; i++) {
        //Extract age and weight data for the current row. Is there a different syntax or approach I should consider?
        var age = ageWeightTbl[i][0];
        var weight = ageWeightTbl[i][1];
        //Check if the weight falls within the specified range
        if (weight > minVal && weight < maxVal) {
            //If it meets the criteria, store the age and weight values in arrays
            ageArray.push(age);
            weightArray.push(weight);
        }
    }
  
    var weightMode = mode(weightArray);
  }

Additional Question: Is there a more user-friendly data format that can be displayed on an HTML page but is easier to manipulate in JavaScript? If so, please provide an overview of its advantages and functionality.

I have included a sample table for testing purposes:

//Function to create a mock table with random data for testing
function generate_table(rows) {
  // Get the body element
  var body = document.getElementsByTagName("body")[0];
 
  // Create table and tbody elements
  var tbl     = document.createElement("table");
  var tblBody = document.createElement("tbody");
 
  // Populate cells in the table
  for (var i = 0; i < rows; i++) {
    // Create a row
    var row = document.createElement("tr");
 
    for (var j = 0; j < 2; j++) {
      // Create a cell and add text content
      var cell = document.createElement("td");
        if (j<1) {
            var cellText = document.createTextNode(""+Math.round(100*Math.random())+"");
        }
        else {
            var cellText = document.createTextNode(""+Math.round(10*Math.random())+"");
        }
      cell.appendChild(cellText);
      row.appendChild(cell);
    }
 
    // Add the row to the table body
    tblBody.appendChild(row);
  }
 
  // Append tbody to table
  tbl.appendChild(tblBody);
  // Append table to body
  body.appendChild(tbl);
  // Set table border attribute
  tbl.setAttribute("border", "2");
}

//Sample Output: {"Mode": 9}

Answer №1

Here's a suggestion to improve your table: Assign an id attribute to it (I inserted the following line into your "mock table" function: tbl.id = "weightAgeTable";).

Next, use the following function and provide the id value as the first argument:

function birthWeightByAge(tableId, rowCount, minVal, maxVal) {
    var weightArray = [];
    var ageArray = [];
    var tbl = document.getElementById(tableId);

    //Iterate through each row in the table
    for (var i =0; i < rowCount; i++) {

        //Retrieve age and weight data from the current row
        var weight = tbl.rows[i].cells[0].innerHTML; 
        var age = tbl.rows[i].cells[1].innerHTML; 

        //Check if the baby's weight falls within the specified range
        if (weight > minVal && weight < maxVal) {
            //If it does, store the age and weight in our arrays
            ageArray.push(age);
            weightArray.push(weight);
        }
    }

    console.log(weightArray); 
}

Since I don't have access to your mode function, I've omitted it and instead displayed the array in the console for demonstration purposes.

Also, it seems like your "mock table" function may have swapped the columns, which is why my references to .cells are reversed compared to yours.

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

Using the @ symbol in jQuery within an MVC framework can be achieved by first ensuring that

I'm attempting to incorporate the @ symbol into a JavaScript if condition, but I keep receiving an error. if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) { alert('yes'); ...

How to Choose Between Landscape and Portrait Printing Modes in Firefox and Internet Explorer 8

Currently, I am using the latest version of FireFox and IE8. In order to change the printing orientation, I utilized the following code in my CSS file: @page { size: portrait; } You can find more information about the @page property here. Although it i ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

Unable to identify the element ID for the jQuery append operation

After attempting to dynamically append a textarea to a div using jQuery, I encountered an issue. Despite the code appearing to work fine, there seems to be a problem when trying to retrieve the width of the textarea using its id, as it returns null. This s ...

When generating a docx file with html-docx-js, it lacks the capability to incorporate external CSS class styles into the document

I have been utilizing the html-docx-js module to convert html content into docx format. However, I am facing an issue where most of my CSS is externally loaded and html-docx-js does not apply any styles. Here is a simplified code sample: const html = &ap ...

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

How to incorporate markdown files as strings in Next.js

Is there a way to bring in markdown files as strings in Next.js for use on both the client and server sides? ...

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

Troubleshooting: React is not defined in Rollup + React 17 with updated JSX Transform

I'm currently working on prototyping a microfrontend architecture using Rollup and multiple create-react-app applications. However, when I try to locally yarn link my external app with the container app, I am encountering the following error: The err ...

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...

Variable Stores the Results of Node.js http.request

Hello everyone, I've been working on a project where I need to pass the results from an https.request in my node.js code to a variable. The https.request is set up to communicate with a SOAP API and receive the response successfully. My main objectiv ...

Ways to conceal components upon clicking a different element

Struggling to make this jQuery function properly. I have a form with all fields contained in a div.form-group. The subscribe button is identified by the id subscribe. I'm aiming to hide the form fields when clicked, but my JavaScript doesn't see ...

I am having trouble specifying a class within an SVG using D3.js

I have been facing a strange issue with my script. When I try to execute the following code: var key="#US" d3.select(key).style("fill", "red"); it seems like it's not working for me. Interestingly, when I run the same co ...