I have two arrays as
array1 = ["a","b","c"];
array2 = ["1","2","3"];
I don't know how to iterate using forEach or map into the table row for an output like this.
array1 array2
a 1
b 2
c 3
using nodejs
Just iterate through one array using forEachand use the index to access the element of the other array.
let array1 = ["a","b","c"];
let array2 = ["1","2","3"];
let tab = document.getElementById('table');
array1.forEach((e,i)=>{
let tr = document.createElement('tr');
let td1 = document.createElement('tr');
let td1text = document.createTextNode(e);
let td1Ele = td1.appendChild(td1text);
tr.appendChild(td1Ele)
let td2 = document.createElement('tr');
let td2text = document.createTextNode(`\t ${array2[i]}`);
let td2Ele = td2.appendChild(td2text);
tr.appendChild(td2Ele)
tab.appendChild(tr);
console.log(e, `\t` , array2[i]);
})
<table id='table'>
</table>
Assuming you have the below HTML snippet (if not, you can add this to your HTML)
<table>
<thead>
<tr>
<td>array1</td>
<td>array2</td>
</tr>
</thead>
<tbody></tbody>
</table>
What you need to do is loop through the arrays using index to access their values. The javascript below is used to generate the table cells in HTML, choose using either a basic for-loop, or use the forEach method as the forEach method exposes the index in its second argument.
var array1 = ['a', 'b', 'c'];
var array2 = ['1', '2', '3'];
var tbody = document.querySelector('tbody');
// either use a for-loop
for (var i = 0; i < array1.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.textContent = array1[i];
td2.textContent = array2[i];
tr.appendChild(td1);
tr.appendChild(td2);
tbody.appendChild(tr);
}
// or the array's forEach method
array1.forEach(function (val, idx) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.textContent = array1[idx];
td2.textContent = array2[idx];
tr.appendChild(td1);
tr.appendChild(td2);
tbody.appendChild(tr);
});
If you mean a html-table, it may be an idea to use a map/reduce solution, something like:
const array1 = ["a","b","c"];
const array2 = ["1","2","3"];
// map columns
const columns = array1.map( (c, i) => [c, array2[i]] );
const table = `
<table>
<tr>
<th>array1</th>
<th>array2</th>
</tr>
${columns
.reduce( (p, [v1, v2]) => p +
`<tr><td class="center">${v1}</td>
<td class="center">${v2}</td></tr>`, "")
}
</table>`;
document.body.innerHTML = table;
body {
font: 14px/23px verdana, arial;
margin: 2rem;
}
td.center {
text-align: center;
}