JavaScript Create Table from Array
This article is for you if you want to create a table from stored data in a JavaScript array. JavaScript provides a powerful and flexible way to create tables dynamically based on arrays, so we can easily retrieve elements from an array to the table. Instead of manually coding each table cell, JavaScript can be used to iterate over an array and populate the table rows and cells based on the array’s content. In this article, we will explore step-by-step how to create tables from arrays using JavaScript.
Which type of array should be used to display a table?
We should not use a one-dimensional array to display a table from an array of elements because it contains only a column of tables. We need rows and columns values to create a table, so we need to create two-dimensional arrays to display a table.
If we use a one-dimensional array all our data will be displayed in a single row as in the above image. So, we have to use a two-dimensional array to display both the rows and columns of the tables.
We can create a table in javascript by using the HTML structure of the table like <table>
, <tr>
, <th>
, and <td>
elements. We need to use the <th>
tag for only the first row of the array to display the header of the table, like:
dataArray[0][0] => indicates 1st row 1st column
dataArray[0][1] => indicates 1st row 2nd column
dataArray[0][2] => indicates 1st row 3rd column
.
.
We need to use <td> tag for except the first row of the array to display table cell, like:
dataArray[1][0] => indicates 2nd row 1st column
dataArray[1][1] => indicates 2nd row 2nd column
dataArray[1][2] => indicates 2nd row 3rd column
.
.
The above example contains the code to display the 2nd row of the table. Similarly, you can use <td> tags for all rows in the array using JavaScript for loop.
How to create a table from an array?
You can create a table from values in a JavaScript array by following these 3 easy steps.
HTML step
We need to create a <div>
tag and set idname
“tableContainer” in HTML to display the table. We’ll create the entire table structure in this element by using javascript.
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript: Create Table from Array</title>
</head>
<style>
//CSS code here...
</style>
<body>
<div id="tableContainer"></div>
</body>
<script>
//JS code here...
</script>
</html>
JS step
Now, let’s dive into the JavaScript step that will generate the table from an array. Paste the below code inside the <script> tags in your HTML file:
- Create an array with data: First, we will create a javascript two-dimensional array and add sample data to it.
- Open the function: Then create a javascript function “
createTable
” with the argument “dataArray
” to display the array data in the table. - Get the table container element: Inside the function, we’ll retrieve the
<div>
element with the IDname “tableContainer
” from the HTML document. It will be the container where the dynamically created table will be placed. - Create the table element: Create a new
<table>
element using the JS document.createElement method. It will serve as the main table container. - Create a loop, table rows, and cells: Create for loop that iterates over each element (row) in the dataArray array. For each row, it creates a new
<tr>
element usingdocument.createElement
. This element will represent a table row. - Create nested loop: Inside the loop, we’ll create another loop that iterates over each element (cell) in the current row of the
dataArray
. For each cell, it creates a new<th>
element if the row indexi
is0
(indicating the header row), or an<td>
element otherwise (for data cells). The cell’s content is set usingdocument.createTextNode
the value fromdataArray[i][j]
. This creates a text node containing the data value, and it is appended to the cell element usingcell.appendChild(cellText)
. Then we’ll append the cell element is then to the current row usingrow.appendChild(cell).
- Append the rows to the table: After creating all the cells for a row, we need to append the row element to the table element using the
table.appendChild(row)
- Close the function: We’ll need to append the entire table structure to the table container element using
tableContainer.appendChild(table)
and close the function. - Call the function: Finally, we have to call the function by using the function name
createTable(dataArray)
.
Code:
// Sample array data
const dataArray = [
['Name', 'Age', 'Country'],
['John Doe', 25, 'USA'],
['Jane Smith', 30, 'Canada'],
['Bob Johnson', 35, 'UK'],
];
// Function to create a table
function createTable(dataArray) {
const tableContainer = document.getElementById('tableContainer');
const table = document.createElement('table');
for (let i = 0; i < dataArray.length; i++) {
const row = document.createElement('tr');
for (let j = 0; j < dataArray[i].length; j++) {
const cell = i === 0 ? document.createElement('th') : document.createElement('td');
const cellText = document.createTextNode(dataArray[i][j]);
cell.appendChild(cellText);
row.appendChild(cell);
}
table.appendChild(row);
}
tableContainer.appendChild(table);
}
// Call the function to create the table
createTable(dataArray);
CSS Step
We need to use CSS to create the border of the table, you can paste this code inside the <style> tag. In the CSS style below, we have set the border for the <table>, <tr>, <th>, and <td> tags separately.
Code:
code:
tr,td, table, th{
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
text-align: center;
font-family: sans-serif;
font-size: 20px;
}
Testing the Code
After applying all these steps, save your HTML file and open it in a web browser our output will display like this:
Conclusion
I hope you guys, by following the step-by-step guide in this article, you have learned how to generate tables from arrays efficiently.