How to remove excess td when using loop javascript - javascript

I am going to generate a table with td colspan.
for(let x = 0; x < rows; x++){
table += "<tr>";
for(let y=0; y < cols; y++){
if(x == 1 && y == 2) {
table += `<td colspan="3">${y}</td>`;
} else {
table += `<td>${y}</td>`;
}
}
table += "</tr>";
}
The problem is when I merge cells using colspan, there is an excess of columns.
https://jsfiddle.net/jL8dq1rg/
How can remove excess column (5,6) so that the columns will be even?
Note: The x & y values are dynamic so as with the colspan. Meaning, any row could have a colspan.

You may for example skip the columns counter when the cell spanning is encountered.
But I see in the meanwhile a similar answer was already delivered.
var table = '';
const rows = 5;
const cols = 6;
for(let x = 0; x < rows; x++){
table += "<tr>";
for(let y=0; y < cols; y++){
//if 2nd row and 3rd column,
if(x == 1 && y == 2) {
//set the cell data to span 3 columns
table += `<td colspan="3">${y}</td>`;
y+=2; //<---- increment the cols counter skipping the cols this cell is spanning across
} else {
table += `<td>${y}</td>`;
}
}
table += "</tr>";
}
document.getElementById('target')
.innerHTML = table;
table td{
border: solid;
}
<table id="target"></table>

for(let x = 0; x < rows; x++){
table += "<tr>";
for(let y=0; y < cols; y++){
if(x == 1 && y == 2) {
table += `<td colspan="3">${y}</td>`;
y+=2 //y+2 End cycle early
} else {
table += `<td>${y}</td>`;
}
}
table += "</tr>";
}

You could work with the "y" variable of your for-loop and add +2 to your variable whenever you add a colspan.
const rows = 5;
const cols = 7;
let table = "<table border='1'>";
for(let x = 0; x < rows; x++){
table += "<tr>";
for(let y=0; y < cols; y++){
if(x == 1 && y == 2) {
table += `<td colspan="3">${y}</td>`;
y += 2
} else {
table += `<td>${y}</td>`;
}
}
table += "</tr>";
}
table += "</table>";
document.getElementById('app').innerHTML = table;

Related

How can I create a Table in JS with "for loops" filled with numbers 1 to 100

I created multiplication table using for loop
now I need to create the same table with numbers 1 to 100 like this one:[table][1]
how do I create this one
[1]: https://i.stack.imgur.com/FAacu.png
document.write('<table border="3">');
for (var x = 1; x < 11; x++) {
document.write("<tr>")
for (let i = 1; i < 11; i++) {
document.write("<td>" + x * i + "</td>")
}
document.write("</td>")
}
document.write("</table>")
You can start x from 0 (to 10) then the formula of the current cell's number is x * 10 + i so for [2,2] cell it would be 1 * 10 + 2
document.write('<table border="3">');
for (let x = 0; x < 10; x++) {
document.write("<tr>")
for (let i = 1; i <= 10; i++) {
document.write("<td>" + (x * 10 + i) + "</td>")
}
document.write("</td>")
}
document.write("</table>")
I have looked into your code and seems like logic inside your for loop is not correct.
I am posting a working code logic for this, I hope this is what you need.
document.write('<table border="3">');
for (var x = 1; x <= 100; x += 10) {
document.write("<tr>");
for (let i = x; i <= x + 9; i++) {
document.write("<td>" + i + "</td>");
}
document.write("</td>");
}
document.write("</table>");

Minesweeper : Problem to recover the mines adjacent to a tile

I've got this problem. My function seems to check outside the borders of my 10x10 board. It's made to return the number of mines around a Tile[row, column] but I get :
minesweeper.js:152 Uncaught TypeError: Cannot read property '0' of undefined
at getAdjacentMines (minesweeper.js:152)
Here is my function, thanks everyone for your time.
function getAdjacentMines(row, col) {
let count = 0;
let minRow = row - 1;
let maxRow = row + 1;
let minCol = col - 1;
let maxCol = col + 1;
if (minRow < 0) minRow = 0;
if (maxRow > board.length) maxRow = board.length - 1;
if (minCol < 0) minCol = 0;
if (maxCol > board.length) maxCol = board.length - 1;
for (row = minRow; row <= maxRow; row++) {
for (col = minCol; col <= maxCol; row++) {
if (board[row][col].boom === true) count++;
}
}
return count;
}
Welcome to Stack overflow!
you seem to have a typo on this section
for (row = minRow; row <= maxRow; row++) {
for (col = minCol; col <= maxCol; row++) {
if (board[row][col].boom === true) count++;
}
}
That needs to be:
// v here
for (col = minCol; col <= maxCol; col++) {
Not:
for (col = minCol; col <= maxCol; row++) {
That means that 'row' will keep increasing until it reaches an index of 10, then it will try to read 'col' (which will be 0) of row 10 (which will be undefined)

Building triangle with nested loops

I'm trying to build a triangle using nested loops.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
I expected that each row is more than the last by only one "#" like this:
But this is the result I got:
The reason your code does it is you are updating line on each iteration and you keep appending to it. If you want to do the nested loops, than you need to reset the variable line each time you are in the outer loop.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line =""
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Or you can keep what you have and dump the inner loop and every iteration you just add one character to the line.
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line += "#";
triangle += line + "\n";
}
console.log(triangle);
You need to empty your line before each nested iteration. Without this you have one line and every time concatenate new items to it. Also you can leave the line variable and just use the triangle.
var triangle = '';
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
triangle += "#";
}
triangle += "\n";
}
console.log(triangle);
You can also try this solution with String#repeat
var triangle = '';
for (var row = 1; row <= 7; row++) {
triangle += '#'.repeat(row) + '\n';
}
console.log(triangle);
function triangle(num) {
for(let i = '#'; i.length < num; i+='#') {
console.log(i)
}
}
Try code below:
function generatePyramid() {
var totalNumberofRows = 7;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
output+= "# ";
}
print(output);
output="";
}
}
generatePyramid();
How it works: http://rextester.com/ULY85622
EDIT: Fixed it by just adding one line - you need to reinitialize the variable "line" after each row iteration
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line="";
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
You need to reset line after each loop because it is accumulating all # on each cycle:
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line = "" // Add this line
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
Your code is incorrect because line follows the following steps on each cycle:
row 1: line starts as '' and ends as # (Adds #)
row 2: line starts as # and ends as ### (Adds ##)
row 3: line starts as ### and ends as ###### (Adds ###)
row 4: line starts as ###### and ends as ########## (Adds ####)
row 5: line starts as ########## and ends as ############### (Adds #####)
row 6: line starts as ############### and ends as ##################### (Adds ######)
row 7: line starts as ##################### and ends as ############################ (Adds #######)

Building a JavaScript grid with odd and even characters using two loops

This is my first question on StackOverflow.
I have to build gridGenerator(num). If num is 3, it would look like this:
#_#
_#_
#_#
If num is 4, it would look like this:
#_#_
_#_#
#_#_
_#_#
I was able to solve it for odd numbers, but struggle to adjust it to even numbers.
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if (row.length % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(3));
Need a hint how to solve it for 2, 4, and other even numbers. Thank you!
Try this
if ((i+j) % 2)
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if ((i+j) % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(4));
You can use the condition num % 2 to determine if a number is even or odd. I would use two loops like you are doing. Make your character addition based on the even / odd state of the row and column. At the end of each row insert the line break.
EDIT: Here you go.
function generateGrid( num ) {
let i, j, grid = "";
for ( i = 0; i < num; i++ ) {
for ( j = 0; j < num; j++ ) {
if ( ( i + j ) % 2 ) {
grid += "_";
} else {
grid += "#";
}
}
grid += "\n";
}
return grid;
}
var grid = generateGrid( 4 );
console.log( grid );
function gridGen(num) {
var even = '';
for (var i = 0; i< num ; i++)
even += (i%2) ? '_' : '#';
odd = even.substring(1) + (num%2 ? '_' : '#');
var out = '';
for (var i = 0; i< num ; i++)
out += ((i%2) ? odd : even) + '\n';
return out;
}
console.log('Even Case');
console.log( gridGen(8));
console.log('Odd Case');
console.log( gridGen(7));
If you are looking for another approach + efficiency try this

2D Arrays in Javascript

For college, we have a problem to solve regarding 2D arrays, however the nature of them has never been cover in class. I've scoured this site for answers(which might be evident in my code) but cannot get it to work, or even truly understand what is going on or why. The exact question is:
Write a program that utilises a 8x8 2-dimensional array.
(a) Initialise the array elements via nested for loops as follows
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
...
...
57 58 59 60 61 62 63 64
(b) Add some code that will display all array elements in an 8x8 HTML table.
(c) Use nested for loops for calculating the sum and the average of the
values stored in the array.
Let a function display these values on screen eg use alert().
The code I have so far is :
x = matrix( 8 , 8, 0 ); // 8 lines, 8 cols filled with empty string
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
var add = 1
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue + add;
}
var add = add + 1
}
return arr;
}
function displayInDiv() {
var output_string_ = "" ;
var lastElement = 64 ;
output_string_ = output_string_
+'<table>'
+'<tr>'
+'<th width="11%" align="left">ARRAY INDEX</th>'
+'<th width="11%" align="right"> array_1</th>'
+'<th width="11%" align="right"> array_2</th>'
+'<th width="11%" align="right"> array_3</th>'
+'<th width="11%" align="right"> array_4</th>'
+'<th width="11%" align="right"> array_5</th>'
+'<th width="11%" align="right"> array_6</th>'
+'<th width="11%" align="right"> array_7</th>'
+'<th width="11%" align="right"> array_8</th>'
+'</tr>'
;
for ( var i = 1 ; i < 9 ; i++ ) {
for ( var j = 0 ; j < 7 ; j++ ) {
output_string_ = output_string_
+'<tr id="table_row_'
+ i
+'">'
+'<td width="11%" align="left">'
+'['
+ i
+']'
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'</tr>'
;
}
output_string_ = output_string_
+'<table>'
;
var output_section_ = document.getElementById("list_");
output_section_.innerHTML = output_string_ ;
}
}
Sorry for the huge text dump, but i'm completely stumped. Any help would be greatly appreciated.
I believe the exact code you're looking for is this
var outer = new Array();
for(var i = 0; i < 8; i++) {
var inner = new Array
for(var j = 0; j < 8; j++) {
inner[j] = (i * 8) + j + 1;
}
outer[i] = inner;
}
console.log(outer);
A 2D array is just an array of arrays, here I labelled them inner and outer.
There are 8 inner arrays of length 8, giving you 64 total entries. The value of each entry is 8 * the outer index (which starts at 0), plus the inner index plus 1 (because it also starts at 0).
This should give you enough information to answer parts b and c yourself, but feel free to comment below if you'd like further help. :)
answer for (a)
var arr = [];
var value = 0;
for(var i = 0; i < 8; i++){
var tempArr = [];
for(var j = 0; j < 8; j++){
tempArr.push(++value);
}
arr.push(tempArr);
}
//`arr` has values initialized with 1 - 64
answer for (b)
var table = "<table>";
for(var i = 0; i < 8; i++){
table += "<tr>";
for(var j = 0; j < 8; j++){
table += "<td>" + arr[i][j] + "</td>";
}
table += "</tr>";
}
table += "</table>";
//assume you have an element with id="tbl" in DOM
document.getElementById("tbl").innerHtml = table;
answer for (c)
var sum = 0 , avg = 0;
for(var i = 0; i < 8; i++){
for(var j = 0; j < 8; j++){
sum += arr[i][j];
}
}
avg = sum / 64;
alert("sum: " + sum + " Average: " + avg);
After you create array you can initialize each of the element with another array.
var myarray=new Array(8)
for (i=0; i <8; i++)
myarray[i]=new Array(8)
Hope this helps.
Cheers !
I made a JSFiddle for this, with comments.
HTML
<button onclick="showCalculations();">Show Calculations!</button>
<div id="container"></div>
JavaScript
//Create the 2-d array
var rows = 8; //Number of rows
var columns = 8; //Number of columns
var list = []; //Array where we will put the data
var index = 0; //Keeps track of which index we're at
for(var i = 0; i < rows; i++){
var rowList = []; //Create sub-array
list.push(rowList); //Add the sub-array to our top-level array
for(var y = 0; y < columns; y++){
index++; //Increment the index
rowList.push(index); //Add the index to the current sub-array
}
}
//Create the Table as HTML string
var table = "<table>"; //Start HTML for table
for(var i = 0; i < list.length; i++){
var row = list[i];
table += "<tr>"; //Start HTML for row
for(var y = 0; y < row.length; y++){
var column = row[y];
table += "<td>" + column + "</td>"; //Table cell with content
}
table += "</tr>"; //End HTML for row
}
table += "</table>"; //End HTML for table
document.getElementById("container").innerHTML = table; //Find element with id container and set HTML to table
//Calculations
var sum = 0; //Keeps track of the sum
var numberOfNumbers = 0; //Keeps track of how many numbers has been summed
for(var i = 0; i < list.length; i++){
var row = list[i];
for(var y = 0; y < row.length; y++){
var column = row[y];
sum += column; //Add to sum
numberOfNumbers++; //Increment amount of numbers
}
}
var avarage = sum / numberOfNumbers; //Calculate avarage
//Function to alert the values
function showCalculations(){
alert("Sum: " + sum + "\nAvarage: " + avarage)
}
Note that the creation of the Table and the calculations can be done in the same for-loop. (Acctually all can be, but then we're not making use of the Array we create).
I correct your code. Html:
<button onclick='run()'>Show</button>
<div id='list_'></div>
And js:
function run() {
x = matrix( 8 , 8, 0 );
alert(x);
displayInDiv(x);
}
function matrix( rows, cols, defaultValue){
var arr = [];
var number = 1;
for(var i = 0; i < rows; i++){
arr.push([]);
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
arr[i][j] = number;
number++;
}
}
return arr;
}
function displayInDiv() {
var output_string_ = "" ;
var lastElement = 64 ;
var output_string_ = '<table>'
for ( var i = 0 ; i < 8 ; i++ ) {
output_string_ += "<tr id='table_row_" + i + "'>";
for ( var j = 0 ; j < 8 ; j++ ) {
output_string_ += '<td width="11%" align="left">' + x[i][j] + '</td>';
}
output_string_ += '</tr>';
}
output_string_ += '</table>';
var output_section_ = document.getElementById("list_");
output_section_.innerHTML = output_string_ ;
}
var num;
var arr = [];
// This for loop populates the array
for (var i = 0; i <= 7; i++) {
arr[i] = [];
for (var j = 0; j <= 7; j++) {
arr[i][j] = i * 8 + j + 1;
}
}
// This function displays the populated array
function displayArr(arr) {
var container = document.getElementById("container");
var append = "<table>";
for (var i = 0; i < arr.length; i++) {
append += "<tr>";
for (var j = 0; j < arr[i].length; j++) {
num = i * 8 + j + 1;
append += "<td>" + num + "</td>";
}
append += "</tr>";
}
container.innerHTML = append;
}
// Alerts the sum of all numbers in the 2d array
function getSum() {
var sum = 0;
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 7; j++) {
sum += i * 8 + j + 1;
}
}
return sum;
}
// Alerts the average of all numbers in the 2d array
function getAvg() {
var totalNumbers = 0;
var avg = 0;
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 7; j++) {
totalNumbers++;
}
}
return getSum() / totalNumbers;
}
alert(getAvg());
alert(getSum());
displayArr(arr);
<section id="container"></section>
EDIT* Added the average and sum functions

Categories

Resources