1

I have a for loop that generates html. I'd for this method to generate the elements randomly. Right now they are cardinally generated i.e. d1, d2, ... di. I want them to follow a random sequence i.e. d1, di, di-3, .. di-k.

         for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){
          html +='\t\t\t\t\t\t<tr>\n'
          html += '\t\t\t\t\t\t<td id="row';
          id   = (1+i-numberOfInputs);
          html += id;
          html +='">\n';
          html += '\t\t\t\t\t\t\t<div id=\"t';
          html += id;
          html +='" class=\"ltarget\">'
          html +='</div>\n' 
          html +='\t\t\t\t\t\t</td >\n'
          html +='\t\t\t\t\t\t<td id=\"d'
          html += id
          html += '\">\n'
          html +=`\t\t\t\t\t\t\t${dlArray[i-numberOfInputs]}\n`;
          html +='\t\t\t\t\t\t\t</td >\n' 
          html +='\t\t\t\t\t\t</tr>\n';
        }

What can I try to accomplish this?

3
  • 1
    Google how to create and shuffle an array of ints, then use arr[i] instead of i. (also there's no need to insert linebreak and tab characters in your HTML, you can use single quotes for inner quotes, and HTML string composition is bad practice in general. You also have a type I guess since you aren't opening the rows with a <tr>) Commented Sep 29, 2021 at 19:02
  • Would an array of objects also work? And then use the object keys as your values for id, #ofinputs, so on. Commented Sep 29, 2021 at 19:06
  • 1
    Can you tell us what the end goal is here? As in, add an example table to your question? Commented Sep 29, 2021 at 19:09

1 Answer 1

1

This is a slightly shorter implementation of the table generator using a Durstenfeld shuffle to generate an arbitrary order of the idx array which is then used to output the elements of the dlArray array:

function shfl(a){
 for(let j,i=a.length;i>1;){
  j=Math.floor(Math.random()*i--);
  if (i!=j) [a[i],a[j]]=[a[j],a[i]]
 }
 return a
}

const dlArray="abcdefghij".split(""),
      idx=[...Array(dlArray.length)].map((_,i)=>i+1);
document.querySelector("div").innerHTML = '<table id="tablestyle">'
 +shfl(idx).map(i=>
   `<td id="row${i}"><div id="t${i}" class="ltarget">${i}</div></td ><td  id="d${i}">${dlArray[i-1]}</td ></tr>`).join("\n")+'</table>';
<div></div>

Sign up to request clarification or add additional context in comments.

2 Comments

I updated the question.
I omitted the \t and \n characters in my solution as they will not make any difference once the HTML is parsed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.