I have a list var words=['ac', 'bd', 'bf','uy','ca'];
I want to form a table of 2 columns listing all these words one after another from left to right.
The result table should be
<table id="wordTable">
<tr>
<td>ac </td> <td>bd </td>
</tr>
<tr>
<td>bf </td> <td>uy </td>
</tr>
<tr>
<td>ca </td> <td> </td>
</tr>
</table>
This javascript code does not work
function showWords(){
row_Index=0;
for (const myWord of words)
{
if (row_Index==0){
document.getElementById("wordTable").innerHTML +="<tr>";
document.getElementById("wordTable").innerHTML += "<td>"+ myWord +"</td>";
}
else if (row_Index==1){
document.getElementById("wordTable").innerHTML += "<td>"+ myWord +"</td>";
document.getElementById("wordTable").innerHTML +="</tr>";
}
else if (row_Index==2){
row_Index=0;
}
row_Index++;
}
}
How to create that table from the list?
Also, how to clear all the rows and columns of the table?
document.getElementById("wordTable").clear();
or document.getElementById("wordTable").remove();
don’t work
3
Answers
Can you please check the below solution? Hope it will work for you.
You could do it with a combination of
.reduce()
and.map
like this:The function parameter
ncols
can be set to any value. Here the value 2 fulfills OP’s requirements.