var MyArray = [['Cats', ['Lion','Tiger','Leopard']], ['Dogs', ['Wolf','Pug']], ['Reptiles', ['Snake','Gecko','Lizard','Triceratops']]];
var MyTable = document.getElementById("results");
const headerRow = document.createElement("tr");
MyTable.appendChild(headerRow);
for(var i=0;i<MyArray.length;i++) {
const newCell = document.createElement("th");
newCell.textContent = MyArray[i][0];
headerRow.appendChild(newCell);
for (const datum of MyArray[i][1]) {
const newRow = document.createElement("tr");
MyTable.appendChild(newRow);
const newCell = document.createElement("td");
newCell.textContent = datum;
newRow.appendChild(newCell);
}
}
<table id='results' border=1></table>
I’m currently trying to turn an array of arrays in Javascript into an HTML table of results. I have it kinda working, but my JS skills with arrays aren’t enough to get the exact results I’m after; any help would be greatly appreciated!
You can see in the snippet that my code is iterating through that array of arrays, extracting the [0] data from each array (the animal class) and building a table with a header row just fine, but the actual data ([1] of each array) is all getting dumped into the first column only, with each entry being a new row.
How do I get the code to put these into separate cells of the new table, bearing in mind the child arrays are all different lengths?
My code is producing a table with all the data in the first column only. What should happen is it produces a table like this:
Cats | Dogs | Reptiles |
---|---|---|
Lion | Wolf | Snake |
Tiger | Pug | Gecko |
Leopard | Lizard | |
Triceratops |
Any guidance gratefully accepted!
4
Answers
Thank you everyone for your help and advice on this. My JS skills are still very much in development, so I'm going to take a little time going through the working examples to improve my knowledge and understand why they work and where my original was going wrong!
My advice on this would be to avoid using tuples like this. Here what you are processing is called a
tuple
array['familyName', ['members']]
and is a bad practice. Generally speaking, in JS, you should work with objects as much as possible.JavaScript offers a lot of tools to help you work with objects and arrays. See the code below where I’m using a
reduce
function to format the array into an object and theMath.max
function to find the largest family length before iterating the whole dataset.Is this what you are looking for?
As others have already said, refactoring the input array would be the best solution. Going of off what you have provided the below solution should work for you.