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

Creating a dynamic number of datasets in Chart JSWith Chart JS

After extensive searching, I thought I was on the verge of finding a solution several times, but unfortunately, no luck! I am aware that a similar question was posted yesterday: React Chartjs, how to handle a dynamic number of datasets, but it remains una ...

Navigating to the next page in Angular JS by clicking "Save and Next" which

Hey there, I'm currently diving into Angular JS and working on a CMS system with it. Right now, we're dealing with around 30 to 40 Objects that we load into a list. Whenever one of these objects is clicked, a Modal Window pops up using the Modal ...

Python_scraping <li style="display: hidden;">

I am having trouble extracting the text from the following HTML using Selenium in Python. <div class="tt"> <ul style="list-style-type:none" id="abs2"> <li> Funeral rites have undergone significant changes due to the ...

Utilizing AngularJS directives with the power of string formatting

Looking at this JSON structure {textTemplate:"Name:{0},Phone:{1}",controls:[{id:1,Name:"Name",type:"text"},{id:2,Name:"Phone",type:"text"}]} I'm unsure how to utilize the directive for converting strings into HTML controls This is what I&apos ...

Optimal placement of JavaScript in an Asp.net MVC application with an extensive reliance on partial views

Where is the ideal placement for JavaScript code that is specific to a partial view? For instance, if I have a partial view (loaded via an ajax call) with some divs and I want to convert those divs into an accordion, would it be more advantageous to includ ...

The dynamic loading of videos through the YouTube API

-Need to load multiple videos onto a page, keeping it simple -Each video has an ID stored in the database accessed via $slide['message'] -Currently only loading one video successfully, others show up as blank -Code is within a loop, attempt ...

Horizontal Accordion Design for Cascading Style Sheets (CSS) Books

I am currently working on developing a page that features a book layout. This page will include tabs that users can expand individually. If you would like to see a working example, you can check out this link: https://codesandbox.io/s/book-layout-l28gh?fi ...

Merge floating and absolute positioning techniques

Creating a calendar exhibiting all events in one div requires precise positioning based on the values of top and height. Let me demonstrate this concept. In the image below, both 6am events are aligned vertically. This alignment issue can be resolved by u ...

Transferring information using pure JavaScript AJAX and retrieving it through a Node API

On the client side, I have the following code: sendMail(e) { e.preventDefault(); var name = document.getElementById('name').value; var contactReason = document.getElementById('contactReason').value; var email = document ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

implementing datepicker on multiple textboxes in jQuery upon button click

I have the ability to show multiple text boxes using jQuery. I am now looking to add a datepicker to those text boxes. Any assistance in finding a solution would be greatly appreciated. Thank you in advance. ...

Generate 2 configurations for webpack

Currently, I am facing a challenge while building a webpack file. The issue arose when I needed to incorporate the 'node' target due to conflicts with an 'fs' function that reads certain files. Subsequently, I decided to split my config ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

Redirect events in Backbone views

Is there a way to navigate to a different page when a specific event is triggered in a View using Backbone? events: { 'click .btn': 'signin' }, render: function() { tmp = this.template(); this.$el.html(tmp); }, signin: func ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

React Native automatically triggers the onPress event when using withNavigation

It seems that onPress should only be triggered by a touch event. Initially, this was the case, but when using withNavigation in a screen outside of the StackNavigator, onPress appears to render automatically. HomeScreen.js function mapStateToProps(state) ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Having trouble showing my Google map using canvas

Can anyone help me with this issue that I'm facing? I am working on a JavaScript web page and trying to show a Google map (Google API) along with a canvas tag in the html body. Currently, the map and canvas are only displaying separately. https://i ...