'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;
}


Solution 1:[1]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave Pritlove