To begin with, it is necessary to determine the source data. Now it is a flat array, so it is not clear where the division into lines occurs.
If you pre-process it and get a two-dimensional array, then the nested arrays will be directly strings and you will immediately understand what data is displayed on which row.
For example, for the current array you can get the following two-dimensional
[ [0, 1, 1, 0], [1, 0, 1, 0], [1, 0, 1, 1], [0, 1, 1, 1], [0, 1] ];
You can get this view using the reduce function.
var maxCountInRow = 4; var processedCells = cells.reduce(function(acc,el,index){ var rowIndex = Math.floor(index/maxCountInRow); acc[rowIndex] = acc[rowIndex] || []; acc[rowIndex].push(el); return acc; }, []);
Now this array can be easily projected onto a list of rows with cells.
processedCells.reduce(function(tbody, cells){ tbody.appendChild(// добавляем создаваемую строку cells.reduce(function(tr, el){ // создаем ячейки var td = document.createElement('td'); td.classList.add(el==0?'dead':'live'); tr.appendChild(td); return tr; }, document.createElement('tr')/*создаем строку*/); ); return tbody; }, tbodyContainer);
If to collect everything, the following will turn out:
var cell = [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1]; var tableContainer = document.querySelector("table"); var tbodyContainer = tableContainer.querySelector("tbody"); var maxCountInRow = 4; var processedCells = cell.reduce(function(acc, el, index) { var rowIndex = Math.floor(index / maxCountInRow); acc[rowIndex] = acc[rowIndex] || []; acc[rowIndex].push(el); return acc; }, []); processedCells.reduce(function(tbody, cells) { tbody.appendChild( // добавляем создаваемую строку cells.reduce(function(tr, el) { // создаем ячейки var td = document.createElement('td'); td.classList.add(el == 0 ? 'dead' : 'live'); tr.appendChild(td); return tr; }, document.createElement('tr') /*создаем строку*/ ) ); return tbody; }, tbodyContainer);
td { width: 20px; height: 20px; background-color: green; } .dead { background-color: red; } .live { background-color: green; }
<table> <tbody> </tbody> </table>
As you can see, two convolutions are performed on the same data in a row, and they can be combined:
var cell = [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1]; var tableContainer = document.querySelector("table"); var tbodyContainer = tableContainer.querySelector("tbody"); var maxCountInRow = 4; cell.reduce(function(tbody, cell, index) { if (index % maxCountInRow == 0) { var tr = document.createElement('tr'); tbody.appendChild(tr); } else { var tr = tbody.querySelector('tr:last-child'); } var td = document.createElement('td'); td.classList.add(cell == 0 ? 'dead' : 'live'); tr.appendChild(td); return tbody; }, tbodyContainer);
td { width: 20px; height: 20px; background-color: green; } .dead { background-color: red; } .live { background-color: green; }
<table> <tbody> </tbody> </table>