I have a set of two for loops. The elements are offset by an initial set of elements numberOfInputs. I'd like to refactor these into a single loop. each array has the same number of elements. They are both of set by the same numberOfInputs.
I've figured out how to do this manually by subtracting the offset when necessary and incrementing by 1 where necessary.
// number of inputs start out as 2.
var numberOfInputs = 2;
// initialize blank html
html = '';
//create key inputs
for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){
html += '<div id="s';
id = (1+i-numberOfInputs);
html += id;
html +='\" class=\"draggyBox-small\">';
html += elArray[i-numberOfInputs];
html +='</div>\n';
}
//create description inputs
html += '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){
html += '<td id="row';
id = (1+i-numberOfInputs);
html += id;
html +='">\n';
html += '\t\t<div id=\"t';
html += id;
html +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html +=dlArray[i-numberOfInputs];
html +='</td >\n </tr>\n';
}
html += '</table>';
Have a loop that creates two chunks of HTML (html_1 and html_2), and append them after the loop finishes:
// initialize blank html
html = '';
//create key inputs
var html_1 = ''
var html_2 = '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){
html_1 += '<div id="s';
var id = (1+i-numberOfInputs);
html_1 += id;
html_1 +='\" class=\"draggyBox-small\">';
html_1 += elArray[i-numberOfInputs];
html_1 +='</div>\n';
html_2 += '<td id="row';
html_2 += id;
html_2 +='">\n';
html_2 += '\t\t<div id=\"t';
html_2 +=i-numberOfInputs;
html_2 +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html_2 +=dlArray[i-numberOfInputs];
html_2 +='</td >\n </tr>\n';
}
html = html_1 + html_2 + '</table>'
You could also simplify this with template literals.
Having two for loops that run against the same index is fine. It doesn't change performance significantly and is easier to understand. However, there are other refactoring that could be done to improve both performance and readability.
Note: You're always subtracting numberOfInputs so there's no reason to add it to begin with.
// assuming `html` and `elArray` had been set earlier
// and that `elArray` is an array of strings
let top = elArray.map((v,i) =>
`<div id="s${i+1}" class="draggyBox-small">${v}</div>`
).join('\n');
let bottom = elArray.map((v,i) =>
`<tr>
<td id="row${i+1}">
<div id="t${i}" class="ltarget"></div>
</td >
<td id="d2">${v}</td >
</tr>`
).join('\n');
html = `${top}
<table id="tablestyle">
${bottom}
</table>
`;
References: