What is the best way to create a table by selecting a number at random from a shuffled array of 16 numbers and then incorporating it into the HTML code

I'm trying to display a table in HTML with 16 cells containing numbers from 1 to 16 in a random order. I am having trouble implementing the part where I need to pop a number from the array. Any help would be greatly appreciated :)

Here's the code I have so far:

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

Answer №1

This particular approach achieves the desired outcome without utilizing array.pop (since that would involve implementing a random shuffle on the array). Instead, it simply employs a nested loop for each row and column, selecting a random element each time and then removing it after use. The use of array.length as a multiplier for the random number (ranging from 0-1) ensures that the random index always remains within the valid range as the array shortens.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: 'require' is undefined in react.production.min.js during production deployment

Greetings! I am encountering some difficulties while trying to build on production: the error "require is not defined" is being caused by react.production.min.js. Below are my webpack.config.js and package.json files: webpack.config.js const path = requi ...

Effortless navigation between components in React JS with smooth scrolling

I am encountering difficulties with implementing smooth scrolling on my landing page. I have tried utilizing various npm packages such as smooth scrollbar, but unfortunately, it is not working as expected. How can I achieve smooth scrolling functionality ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...

When using @font-face, Chrome supports it while IE and Firefox do not

I am finding this quite perplexing. I am currently using font-squirrel to download a web kit in order to display a custom font. You can access the font through this link: If you visit the homepage now: The main text in the center reads "Custom Built Webs ...

Styling React components using class names

Struggling with implementing a sidebar feature using the guidance provided in this example. However, I am facing difficulty in applying the necessary styles to each className... Here's what I've attempted so far, but unfortunately, no styles see ...

Eliminating the admin-bar.php styling in a WordPress theme

Currently, I am working on developing my very first WordPress template. I have encountered an issue with the top navigation being pushed down by a specific style rule: html { margin-top: 32px !important; } After investigating further, I discovered that t ...

Utilizing the 'new' operator in the creation of Mongoose schema structures

Trying to figure out the discrepancy between the two methods of Schema creation in mongoose. Despite searching through the documentation and using Google, I haven't been able to find any substantial results. As a beginner in mongoose, I'm curious ...

Struggling to implement a seamless scrolling effect using CSSTransition Group

In my quest to achieve a smooth vertical scroll effect for content appearing and disappearing from the DOM, I've turned to CSSTransitionGroup (or ReactTransitionGroup). While I'm familiar with CSS animations for such effects, I need to implement ...

Prevent image upload until text is clicked on

When the user clicks on the mask image, a file upload dialog box is displayed. Once the user uploads an image, the text "Remove Image" is shown. Issue: Currently, users can upload another image before clicking on "Remove image". However, after clicking o ...

Creating a function in AngularJS to select all checkboxes

I recently started working with Angular and I implemented a select all checkbox that checks all the boxes using ng-model/ng-checked. <th> <input type="checkbox" id="selectAll" ng-model="selectAll"/> </th> <th ...

How come there is such a large space for clicking between my logo and the navigation bar, and what can be done to eliminate it?

* { box-sizing: border-box; padding: 0; margin: 0; } ul { list-style-type: none; } .nav-links, .logo { text-decoration: none; color: #000; } .logo { max-width: 80%; width: 20%; height: 20%; } .navbar img { width: 10%; height: auto; di ...

The sliding div unites with the bottom button, rather than the top one

When hovering over the upper left button, a div with sample description slides down. However, I am facing two challenges that I cannot seem to resolve. The description is supposed to merge with the second button but instead merges with the first one. I a ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...

Can someone please advise me on how to output the value of a var_dump for an array using console.log?

After writing the code in this manner, it functions properly and returns a JSON object. public function getElementsAction() { $currency = App::$app->getProperty('currency'); if(!empty($_POST)) { $sql = 'SELECT name, p ...

Guide on toggling the expansion and collapse of antd TreeSelect items when a button is clicked

I recently started using the antd library to develop my website. I have successfully implemented the TreeSelect component to display nested options. However, I am currently facing an issue: I am attempting to expand and collapse TreeSelect items when a b ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

Setting the height of the text area in a three-column layout cannot be achieved using a percentage value

I'm working on creating a 3-column layout with two text areas. The issue I'm facing is that when I adjust the width of the text areas to create columns, the height shrinks. I need a solution that will be compatible with HTML5 browsers - support f ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

Why isn't margin working with position: fixed?

I need help finding a solution for incorporating margin in a box within my App class. The issue is that the position fixed property doesn't seem to work as intended. <div className="App"> <div className="box"> ...