Improve table rendering, fastest table render - javascript

So I have to render a table with 1000 rows and 1000 columns. Accordingly this link, it seems like the best way is to build the HTML string in javascript and then inserted it into the DOM all in one go. I made a simple example of this, and compare it with couple other methods. At the end, this is really the fastest way which I came out with. But still this is not satisfying enough. So my question is, is there a faster way, than the following example.
var startTime = new Date().getTime(),
tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div'),
finalResult = 0,
endTime = 0,
result = 0;
for (row = 0; row < 1000; row += 1) {
tableString += "<tr>";
for (col = 0; col < 1000; col += 1) {
tableString += "<td>" + "testing" + "</td>";
}
tableString += "</tr";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
endTime = new Date().getTime();
console.log(endTime - startTime);

A massive amount of string concatenation will get you into runtime trouble, no matter what language.
The fastet way will be to go through the native JavaScript DOM API, while constructing your table within a document fragment. At the end of your function, insert that document fragment at the desired position in your document.
Something like this will create a table with 1000 rows and 20 cells per row:
function makeTable() {
var fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i++) {
var row = document.createElement('tr');
fragment.appendChild(row);
for (var j = 0; j < 20; j++) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(i.toString() + ', ' + j.toString()));
row.appendChild(cell);
}
}
var target = document.getElementById('target');
target.appendChild(fragment);
}
JSFiddle: http://jsfiddle.net/KbNLb/4/
EDIT Just saw you did 1000x1000 - that is one million cells, that will be slow no matter what. I really hope on million table cells is not your actual use case. ;-)

Related

Multiplication table in a console for entered number

Good day,
I need to make a method that makes the multiplication table in console.log.
This method should receive a number to which it outputs the multiplication table.
The table should be appeared in the console (console.log). For example, if the number 5 came to the input, we get:
Important note:
In the last line between the numbers, exactly one space should be output.
In each column, the numbers should be aligned to the right.
I have searched everywhere, but I have not found a similar solution to this particular problem anywhere.
I don't quite understand how we can indent and add numbers on the sides. I only got it this way:
function multiplicationTable(value) {
let table = '';
for (let i = 1; i <= value; i++) {
let tableString = '';
for (let j = 1; j <= value; j++) {
tableString += ' ' + (i * j) + ' ';
}
tableString += '\n';
table += tableString;
}
return table;
}
console.log(multiplicationTable(5));
Try something like this :
function multiplicationTable(value) {
let table = '\n';
let maxLength = (value * value).toString().length;
for (let i = 0; i <= value; i++) {
let tableString = '';
for (let j = 0; j <= value; j++) {
let product = i * j;
let padding = ' '.repeat(maxLength - product.toString().length + 1);
tableString += padding + (product || ' ');
}
table += tableString + '\n';
}
console.log(table);
}
multiplicationTable(5);
Explanation :
let table = '\n'; creates an empty string with a newline character, which will be used to store the multiplication table.
let maxLength = (value * value).toString().length; finds the length of the largest number that will appear in the table, which is value * value. This length will be used to set the width of each column in the table.
for (let i = 0; i <= value; i++) creates a for loop that will iterate value + 1 times, where i is the row number. The 0 in i = 0 is because we want the first row to display the column headers (i.e. the numbers 0, 1, 2, ..., value).
let tableString = ''; creates an empty string that will be used to store each row of the table.
for (let j = 0; j <= value; j++) creates a nested for loop that will iterate value + 1 times, where j is the column number. The 0 in j = 0 is because we want the first column to display the row headers (i.e. the numbers 0, 1, 2, ..., value).
let product = i * j; calculates the product of the row and column numbers, which is the number that will appear in the table at that position.
let padding = ' '.repeat(maxLength - product.toString().length + 1); adds spaces to the left of the product so that each column has the same width. maxLength is the width of each column, and product.toString().length is the length of the product. The + 1 in maxLength - product.toString().length + 1 adds an extra space to the left of each product.
tableString += padding + (product || ' '); adds the padding and product (or an empty string, ' ', if i or j is 0) to the tableString. This creates the row of the table.
table += tableString + '\n'; adds the tableString and a newline character to the table. This creates a new row in the table.

How to create a user generated matrix in javascript/html while having the table label each cell incrementally

Well hello hello everyone, new to javascript. I received an assignment and am at a bit of a standstill. I need to have a user-generated table that labels itself. I am having a hard enough time getting the table to generate properly with the input from prompts. Now I am also stuck with the loop needed for the labeled rows and columns as well. It May seem ridiculous how simple this is but I am exhausted and receiving little guidance and could use the help.
The table should look like this. I can't even get the table to generate properly with loops yet.
[1][2][3][4]
[5][6][7][8]
<!DOCTYPE html>
<script>
var row = prompt("how many rows would you like?");
var col = prompt("how many colums would you like?");
</script>
<body>
<script>
var mytable = "";
var cellNum = 0;
for (var r = 0; r < row ; r++);
{
mytable += "<tr>";
for (var c = 0 ; c < col; c++ );
{
mytable += "<td>" + cellNum++; + "</td>";
}
mytable += "</tr>";
}
document.write("<table border=1>" + mytable + "</table>");
</script>
</body>
You basically put a semicolon behind the first for loop.
for (var c = 0 ; c < col; c++ );
Right version would be this piece of code:
for (var c = 0 ; c < col; c++ )
I also would change
for (var r = 0; r < row ; r++)
into
for (var r = 0; r < row-1 ; r++)
or you gonna end up with a empty row.
Have a great day!
the answer has already been put above. Just a fun take from my side as well.
How about we create some huge amount of cells and show only part of them depending on input. I've used flex container to conditionally set styles.
The fiddle: https://jsfiddle.net/42c1mep8/30/
Cheers!
just remove semicolons from the for loop.
var mytable = "";
var cellNum=0, row=3, col=4;
for (var r = 0; r < row ; r++) {
mytable += "<tr>";
for (var c = 0 ; c < col; c++ ) {
mytable += "<td>" + (++cellNum) + "</td>";
}
mytable += "</tr>";
}
document.write("<table border=1>" + mytable + "</table>");

Using Javascript create table (tableee added)

I'm putting tableee's(a list contains 36 elements) elements into my table(which is x) ,but It's would be a 6*6 matrix not just 1*1 matrix.
wrong
I need(just a likely example)
var x = document.createElement('table');
var y = document.createElement("tr");
var z = document.createElement("td");
document.body.appendChild(x);
for (var i=0; i<tableee.length; i++){
x.appendChild(y);
y.appendChild(z);
var t = document.createTextNode("why");
z.appendChild(t);
}
//console.log(tableee);
document.getElementById("table1").innerHTML = x;
I don't know what tableee is, but since you only use the length I've changed it to two variables rows and columns.
This should create the table structure you are looking for:
var columns = 6;
var rows = 6;
var table = document.createElement('table');
var tbody = document.createElement('tbody');
for (var i = 0; i < rows; i++){
var row = document.createElement('tr');
for (var j = 0; j < columns; j++){
var column = document.createElement('td');
var text = document.createTextNode('text');
column.appendChild(text);
row.appendChild(column);
}
tbody.appendChild(row);
}
table.appendChild(tbody);
document.body.appendChild(table);
table td {
border: 1px solid black;
padding: 2px 4px;
}
Also, it's a better idea to append the table to the document body at the end to avoid reflow/repaint calls on every iteration.
Thank you for providing the content of the variable tableee. So in my opinion I think you can use template strings (ES6 feature) to print all the content of the array but you will tweak the array to subdivide it into sub arrays
I made it programmatically but if you have direct access to the array, feel free to edit first to have the same form as in the code comments:
function splitarray(input) {
var output = [];
for (var i = 0; i < input.length; i += 6) {
output[output.length] = input.slice(i, i + 6);
}
return output;
}
// this is a dummie array I made up according to your tablee data in the screenshots
var tableee = ['1year', '2year', '3year', '4year', '5year', 'rate1%', '1.0100', '1.0201', '1.0303', '1.0406', '1.0510', 'rate2%', '1.0100', '1.0201', '1.0303', '1.0406', '1.0510', 'rate3%', '1.0100', '1.0201', '1.0303', '1.0406', '1.0510', 'rate4%', '1.0100', '1.0201', '1.0303', '1.0406', '1.0510', 'rate5%', '1.0100', '1.0201', '1.0303', '1.0406', '1.0510'];
// This is to add an empty string at the beginning of the array
tableee.unshift('');
// This is to slice the array into sub-array that have lenght of 6 each (to fit the required table)
// The array will have the form of [ [...](6), [...](6), [...](6), [...](6), [...](6), [...](6) ](6)
var newTableee = splitarray(tableee);
var x = '<table border="1"> <tbody>';
for (var i = 0; i < newTableee.length; i++) {
x += '<tr>';
for (var j = 0; j < 6; j++) {
x += `<td> ${newTableee[i][j]} </td>`; // Here is the use of template strings
}
x += '</tr>';
}
x += '</tbody> </table>';
document.getElementById('table1').innerHTML = x;
<div id="table1"></div>
hopefully this is a more specific answer to your issue.

Creating a dynamic table in JavaScript

I am trying to create a dynamic table using JavaScript. I need the table to take the form of a scheduler (hour blocks for 24 hours) It has to span a full 24 columns for the hours with a header for each block. 12am, 1am...11pm, etc. However, I'm currently restricted to the first col for the headers. My knowledge of JavaScript is at a beginner level. This is a basic representation of what I need and what is broken. What would be the best way to fix this code or implement something better?
function populateTable(table, time, rows, cells, content) {
if (!table) table = document.createElement('table');
var head = document.createElement('thead');
var title = document.createElement('th');
head.appendChild(title);
for (var x = 1; x <= time; x++){
table.appendChild(head);
title.appendChild(document.createTextNode(x));
}
var body = document.createElement('tbody');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
$(document).ready(function () {
document.getElementById('scheduleTable')
.appendChild(populateTable(null,12,12, 12, "content"));
});
Need to change the top part to:
var head = document.createElement('thead');
table.appendChild(head);
for (var x = 1; x <= time; x++) {
var title = document.createElement('th');
title.appendChild(document.createTextNode(x));
head.appendChild(title);
}
If you want the title cells to be spread out correctly.

Beginning JavaScript - create table

I have to create an array using a for loop to produce the numbers 0-24. Then print these numbers in order in a 5x5 "table" using a for loop.
The output should be: 0 1 2 3 4 x 5 6 7 8 9 x 10 11 12 13 14 x... 20 21 22 23 24
I can't figure out how to create the table.
Here is my code:
// Calculate numbers 0-24
var numbers = [];
for (var 0; i < 25; i++) {
numbers[i] = i;
}
// Create table
for (var row = 0; row < 4; row++) {
document.write('<tr>');
for (var col = 0; col < 4; col++) {
document.write('<td>' + numbers + '</td>');
}
document.write('</tr>');
}
The problem is that you are accessing the array without any index. Try this instead:
var numbers = [];
for ( var 0; i<25; i++)
{
numbers[i]= i;
}
//Create table
var i = 0;
var table = "<table>";
for (var row=0; row<5; row++) //Changed from 4 to 5
{
table += "<tr>";
for (var col=0; col<5; col++) //Changed from 4 to 5
{
table += "<td>" + numbers[i] + "</td>"; //numbers to numbers[i]
i++;
}
table += "</tr>";
}
table += "</table>";
document.write(table);
Update: Taking from what #Jon P answered I updated my answer to only write once.
This looks like a homework assignment so I'll make some suggestions instead of an out right answer.
Dont use document.write.
Create a table stub on the page using HTML and give it an ID. Find out how to get element by id. Find out how to update the inner html of that element. Only update the document once.
Use a tool like Firebug for Firefox or Developer tools for Chrome to inspect what is rendered to the page so you can work out what went wrong (or right).
Start your search for knowledge here: https://developer.mozilla.org/en-US/docs/Web/JavaScript
For an added bonus you may be able to do this without nested for loops with the help of the % operator
Supremely overkill, but maybe you will find these functions useful!
// creates an array that contains a sequence of numbers from 0 to size-1
function range(size) {
size = Math.max(0, size);
var result = [];
while (size--) { result.unshift(size); }
return result;
}
// splits an array into chunks of a certain size.
function chunk(array, size) {
if (!array || !array.length || size < 1) { return array };
return [array.slice(0, size)].concat(chunk(array.slice(size), size));
}
// takes a 2D array and converts it to an HTML table.
function createHTMLTable(table) {
var html = table.map(function(row) {
row = row.map(function(cell) { return "<td>"+ cell +"</td>"; });
row = row.join('');
return "<tr>"+ row +"</tr>";
});
html = html.join('');
return "<table>"+ html +"</table>";
}
function renderHTML(html) {
document.write(html);
}
var numbers = range(25);
var table = chunk(numbers, 5);
var tableHTML = createHTMLTable(table);
renderHTML(tableHTML);

Categories