I am seeking to create a table that will take an array with 3 items separated by commas and have them inserted in to a table. Currently my table either fails, or will present the items all grouped together. Under each heading I have one row each filled with "Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002" under the three headings of Country, Capital, Population, I would like 3 rows separated for each heading.
<html>
<head>
<title> </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<table id="table" border="1">
<!-- The Row Number 0 -->
<tr>
<th>City</th>
<th>Country</th>
<th>Population</th>
</tr>
</table>
<script>
var array = [
["Madrid,Spain,3255944", "Santiago,Chile,4837295",
"Lima,Peru,7737002"],
],
var a = array.split(',')
a[0], a[1], a[2];
table = document.getElementById("table");
for(var i = 0; i < array.length; i++)
{
// create a new row
var newRow = table.insertRow(table.length);
for(var j = 0; j < array[i].length; j++)
{
// create a new cell
var cell = newRow.insertCell(j);
// add value to the cell
cell.innerHTML = array[i][j];
}
}
</script>
</body>
</html>
2 Answers 2
You need to call split() on the strings in the array, not the array itself.
array.forEach(row => {
cols = row.split(",");
newRow = table.insertRow(table.length());
cols.forEach(col => {
var cell = newRow.insertCell(newRow.length);
cell.innerHTML = col;
});
});
Comments
Barmars answer is certainly correct but beyond my ken, I do appreciate it. Another source provided the following which is slightly easier to grasp that worked for me beginner self. Below is more towards the use of a learner such as myself and I will correct it and provide the full code once I complete my task, great thanks for the gentleman taking his time and I shall seek to learn my about the syntax when time allows.
var array = [
"Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002"
];
table = document.getElementById("table");
var x;
for (var i = 0; i < array.length; i++){
<tr>
x = arr[i];
var pieces = array.split(',');
<td> pieces[0] </td>
<td> pieces[1] </td>
<td> pieces[2] </td>
</tr>;
}
split()is for strings, not arrays.var array = ["Madrid,Spain,3255944", "Santiago,Chile,4837295", "Lima,Peru,7737002"];var arraya two-dimensional array of strings? Or better, is that intentional?