Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
how can i build table by poping a number from shuffled array of 16 numbers and insert it into the HTML?

I Need to render a table to the HTML with 16 cells containing numbers from 1 to 16 in a random order, the question said that you should pop a number from the array and i cant figure it out how to do it, tnx for the help :)

here is my code

"use strict";

let numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let shuffled = shuffleArr(numArr);

function shuffleArr(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  console.log(arr);
  return arr;
}

function renderTable(arr) {
  let strHTML = "";
  for (let i = 0; i < arr.length / 2; i++) {
    strHTML += "<tr>";
    for (let j = 0; j < arr.length / 2; j++) {
      strHTML += `<td></td>`;
    }
    strHTML += "</tr>";
  }

  let elTable = document.querySelector(".board");
  elTable.innerHTML = strHTML;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This method achieves the end goal but does not use array.pop (which would require the complexity of a random shuffle on the array (see How to randomize (shuffle) a JavaScript array?)

It simply iterates through a nested loop for each row and column, choosing a random element each time, with that element being removed once used. Note, array.length as a mulitplier for the random number (range 0-1) takes care of the random index always been in range for the shortening array.

let numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

let rows=4;
let cols=4;

let markup = "";
let randomIndex = 0;

for (let row=0; row<rows; row++) {
  markup += "<tr>"
  for (let col=0; col<cols; col++) {
   randomIndex = Math.floor(Math.random()*numArr.length);
   markup += `<td>${numArr[randomIndex]}</td>`;
   numArr.splice(randomIndex, 1); // removed used value;  
  } // next col;
  markup += "</tr>";
} // next row; 

const table = document.createElement('table');
table.innerHTML = markup;

document.body.appendChild(table);
table, td {
  border: 1px solid black;
  font-family: monospace;
  text-align: right;
}

table {
  border-collapse: collapse;
}

td {
  width: 2em;
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!