Search code examples
javascripthtmlarrayshtml-table

Create one HTML table from multiple arrays


I’m trying to create an HTMl table from data from several tables with values and the length of values in different arrays are the same. I will simplify the example here by limiting it to two tables.

I would like to get something like this:

enter image description here

But with my code I have : enter image description here

Moreover I dont' know how to add the average line and fill this under the age and I tried just with name and age to do easy. If someone can Help me :)

JS:

let names = ["X","Y"]
let ages = [22,10]

const newTable = document.createElement("table");
    newTable.innerHTML = "<thead><th>Name</th><th>Index</th></thead>";
    for (let name of names) {

      let newRow = document.createElement("tr");
      const tdName= document.createElement("td");
      tdName.textContent = name;
      newRow.appendChild(tdName);
      newTable.appendChild(newRow);
    }

    for (let age of ages ) {

      let newRow = document.createElement("tr");
      const tdAge= document.createElement("td");
      tdAge.textContent = String(age);
      newRow.appendChild(tdAge);
      newTable.appendChild(newRow);
    }

    const target = document.getElementById('target');
    target.appendChild(newTable);
  }

HTML:

<div id="target"></div>

Solution

  • Don't create a new row for each name and age; you want a row for each "set" of items,so loop over the length (checking that they match) and then create a cell for each corresponding array item.

    let names = ["X", "Y"]
    let ages = [22, 10]
    
    const newTable = document.createElement("table");
    newTable.innerHTML = "<thead><th>Name</th><th>Index</th></thead>";
    
    if (names.length == ages.length) {
      for (let i = 0; i < names.length; i++) {
    
        let newRow = document.createElement("tr");
        //name
        const tdName = document.createElement("td");
        tdName.textContent = names[i];
        newRow.appendChild(tdName);
        //age
        const tdAge = document.createElement("td");
        tdAge.textContent = String(ages[i]);
        newRow.appendChild(tdAge);
        newTable.appendChild(newRow);
      }
    }
    const target = document.getElementById('target');
    target.appendChild(newTable);
    <div id="target"></div>