0

I wrote this code to display a table of random numbers between two values using vanilla JavaScript, I used an array to store the random values, and then I displayed them on the page using tales. and I want to count the number of occurrences of every number in this table and display that number. I tried to use a for loop but it didn't work. Can anybody help?

//Variables Exercice 3
var dim = document.getElementById("dimensions");
var min = document.getElementById("min");
var max = document.getElementById("max");
var table = document.getElementById("table");
var btn = document.getElementById("btn");
//Function Exercice 3
btn.addEventListener("click", generate);

function generate() {
  if (dim.value == "" || min.value == "" || max.value == "") {
    alert("Merci de remplir tous les champs");
  } else if (
    Number(min.value) > Number(max.value) ||
    Number(min.value) == Number(max.value)
  ) {
    alert("La valeur minimale doit être inférieur à la valeur maximale");
  } else {
    for (var j = 0; j < Math.floor(dim.value / 10); j++) {
      var row = document.createElement("tr");
      for (var i = 0; i < 10; i++) {
        var arr = [];
        var cell = document.createElement("td");
        while (arr.length < dim.value) {
          var r = Math.floor(
            Math.random() * (Number(max.value) - Number(min.value)) +
            Number(min.value)
          );
          arr.push(r);
        }
        table.append(row);
        row.append(cell);
        cell.innerHTML = arr[i];
      }
    }
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Examen 4 JavaScript</title>
</head>

<body>
  <div class="Ex1">
    <form>
      <h1>Exercice 3</h1>
      <div class="container">
        <div class="dimensions">
          <label for="dimensions">Dimension du tableau</label>
          <input type="text" name="dimensions" id="dimensions" pattern="[0-9]+" title="Merci de fournir que des numéros" />
        </div>
        <div class="min">
          <label for="min">La valeur minimale</label>
          <input type="text" name="min" id="min" pattern="[0-9]+" title="Merci de fournir que des numéros" />
        </div>
        <div class="max">
          <label for="max">La valeur maximale</label>
          <input type="text" name="max" id="max" pattern="[0-9]+" title="Merci de fournir que des numéros" />
        </div>
      </div>
      <button type="button" id="btn">Générez un tableau</button>
      <table id="table"></table>
    </form>
  </div>
  <script src="main.js"></script>
</body>

</html>
  • You declare `arr` inside the loop, so it gets overwritten in every iteration. I think you'd be better off just creating the array in one loop, then writing the array to HTML in another. – Heretic Monkey Jun 08 '21 at 20:19
  • I am trying to understand for whatever dimension does the user add, you want to generate 10 arrays of same length right? – jateen Jun 08 '21 at 20:32
  • I want every line of the table to contain only 10 numbers – Fares Riahi Jun 08 '21 at 20:39

1 Answers1

0

The problem is you're trying to generate your random numbers at the same time that you're building your table. In programming, it's generally easier to break your process into individual steps and do them one at a time. So your program could be:

  1. Generate random numbers.
  2. Count the frequency of the numbers.
  3. Build the table.

// Sample list of numbers.
const numbers = [1, 1, 4, 1, 6, 3, 1, 5, 4, 2, 2, 2, 2];

// Array.prototype.reduce iterates over an array 
// and turns it into something else, called the accumulator.
const frequency = numbers.reduce((acc, item) => {
  // This tertiary statement says to add one to whatever 
  // is at acc[item] if it exists, or just set acc[item] to one.
  acc[item] = acc[item] ? acc[item] + 1 : 1;
  return acc;
}, {});

console.log(frequency);
const table = document.querySelector("table");
let i = 0;
for (let rowIndex = 0; rowIndex <= Math.floor(numbers.length / 10); rowIndex++) {
  const row = document.createElement("tr");
  for (let cellIndex = 0; cellIndex < 10; cellIndex++) {
    const cell = document.createElement("td");
    cell.innerText = numbers[i];
    const sub = document.createElement("sub");
    sub.innerText = frequency[numbers[i]];
    cell.append(sub);
    row.append(cell);
    i++;
    if (i >= numbers.length) {
      break;
    }
  }
  table.append(row);
}
<table></table>

It doesn't matter if the numbers are type string or type number, so long as all are the same. You could populate the numbers array with the result of a querySelectorAll from the table, or from the arr variable you're setting in your loop.

Charlie Bamford
  • 1,268
  • 5
  • 18