Home > database >  Iterating two loops using forEach
Iterating two loops using forEach

Time:04-09

I have two arrays like below and implemented the iterations using old for loop approach. However, how can I get the same in forEach().

var questions =['your name', 'SkillSet', 'exp']
var answers =['King', 'Nodejs', '5']

for(let i = 0; i<questions.length; i  ){
htmlobj  = '<tr><th>' questions[i] '</th></tr>'
htmlobj  = '<tr><th>' answers[i] '</th></tr>'
}

CodePudding user response:

I pretty much consider a .forEach() loop to be obsolete these days because a for loop is so much more flexible. With modern Javascript, you can use for/of and still get value and index:

const questions =['your name', 'SkillSet', 'exp']
const answers =['King', 'Nodejs', '5']
let htmlobj = "";

for (const [index, question] of questions.entries()) {
    htmlobj  = `<tr><th>${question}</th></tr><tr><th>${answers[index]}</th></tr>`;
}

console.log(htmlobj);

While the additional flow control advantages of a for loop aren't being used here, they are very useful in many other circumstances and the regular for loop doesn't incur the function overhead of calling a callback function for every iteration of the loop.


And, if you want one row for each question and answer, you would need to change the HTML like this:

    const questions =['Your Name', 'SkillSet', 'Exp']
    const answers =['King', 'Nodejs', '5']
    let htmlobj = "";

    for (const [index, question] of questions.entries()) {
        htmlobj  = `<tr><th>${question}</th><th>${answers[index]}</th></tr>`;
    }

    document.getElementById("result").innerHTML = htmlobj;
table {
    border-collapse: collapse;
}
th {
    text-align: left; 
    border-bottom: 1px solid;
    margin: 0;
    padding: 10px;
}
<table id=result></table>

CodePudding user response:

let htmlobj = ""
questions.forEach((el, index) => {
  htmlobj  = '<tr><th>' el '</th></tr>'
  htmlobj  = '<tr><th>' answers[index] '</th></tr>'
})
  • Related