I have the following arrangement
const arr = ['t1', 't2', 't3', 't4', 't5', 't6', 't7','t8','t9'];
I would like to display it as follows, i.e. limit it to 4 columns and N rows:
table {
font-family: 'Verdana';
padding: 25px;
}
td {
border: 2px solid rgba(0, 0, 0, 0.08);
color: rgba(0, 0, 0, 0.6);
padding: 25px;
}
<table>
<tbody>
<tr>
<td>t1</td>
<td>t2</td>
<td>t3</td>
<td>t4</td>
</tr>
<tr>
<td>t5</td>
<td>t6</td>
<td>t7</td>
<td>t8</td>
</tr>
<tr>
<td>t8</td>
</tr>
</tbody>
</table>
I'm trying this but what happens is that it repeats the elements to me a lot of times and I can't solve it:
let cols = 4;
const arr = ['t1', 't2', 't3', 't4', 't5', 't6', 't7','t8','t9'];
const tBody = document.getElementById('table-content');
arr.forEach((row) => {
let i = 0;
const itemsToRender = arr.slice(i, cols);
if (i === 0) {
i = cols;
} else {
cols *= 2;
i = cols / 2;
}
const newRow = tBody.insertRow();
itemsToRender.forEach((col, index) => {
const newCell = newRow.insertCell(index);
const cellValue = document.createTextNode(row);
newCell.appendChild(cellValue);
});
});
table {
font-family: 'Verdana';
padding: 25px;
}
td {
border: 2px solid rgba(0, 0, 0, 0.08);
color: rgba(0, 0, 0, 0.6);
padding: 25px;
}
<table>
<tbody id="table-content">
</tbody>
</table>
Trying with array methods:
In the end, it turned out to be simpler than I expected, since we are traversing the array, element by element, it is not necessary to create subarrays, simply analyze when it is necessary to create a row.
Or, you can loop by rows to create, using
arr.slice()
to get the corresponding elements.Note: Check the comments at the end of the javascript code, they are just array functions; The way to get the chunks is a bit complicated , but the same idea of the previous example applies... in a single line.
Instead of looping through the array, it's easier to figure out how many rows to create and do two loops, one for rows and one for cells, updating the index every time a new cell is created.
A simpler and more elegant solution is to make use of recursion . This way you call the function with a narrower version of the array until there are no elements in it: