TransWikia.com

JS get random value from array and update array

Stack Overflow Asked by Nicolas Schmit on December 27, 2020

I need your help on this!
I’m generating an array which corresponds to a question number.

var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}

then I use this number to append the corresponding question, answer then click.
Then I’m getting a new value from the array like this

const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);

It works and a new question is charged but the array is still the same.
I’ve tried this

var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);

But It doesn’t work ;-(

Thanks a lot for your help.
Nicolas

Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.

<!DOCTYPE HTML>
<!--
    Hyperspace by HTML5 UP
    html5up.net | @ajlkn
    Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>

<head>
    <title>Repérez vos messages contraignants - Quiz</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="assets/css/main.css" />
    <noscript>
        <link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>

<body class="is-preload">
    <!-- Sidebar -->
    <!-- <section id="sidebar">
    </section> -->
    <!-- Wrapper -->
    <div id="wrapper">
        <!-- Intro -->
        <section id="intro" class="wrapper style1 fullscreen fade-up">
            <div class="inner">
                <header>
                    <button id="start">Commencer</button>
                    <p>&nbsp;</p>
                </header>
                <form action="" method="post">
                    <p id="Qnum"></p>
                    <p id="Q" data-qnumber="" data-type=""></p>
                    <section id="answer">
                        <input type="submit" id="1" name="R1" value="Non">
                        <input type="submit" id="2" name="R2" value="Parfois">
                        <input type="submit" id="3" name="R3" value="Souvent">
                        <input type="submit" id="4" name="R4" value="Oui">
                    </section>
                </form>
            </div>
        </section>
        <!-- Footer -->
        <!-- Scripts -->
        <script src="assets/js/jquery.min.js"></script>
        <script src="assets/js/jquery.scrollex.min.js"></script>
        <script src="assets/js/jquery.scrolly.min.js"></script>
        <script src="assets/js/browser.min.js"></script>
        <script src="assets/js/breakpoints.min.js"></script>
        <script src="assets/js/util.js"></script>
        <script src="assets/js/main.js"></script>
        <script>
        $(document).ready(function() {

            if (localStorage.getItem("clic") >= 45) {
                console.log('45');
                sessionStorage.clear();
                localStorage.clear();
            }

            var Q1 = [1, "My first question", "FP"];
            var Q2 = [2, "My second question", "SP"];
            var Q3 = [3, "My third question", "SE"];
            var Q4 = [4, "My foutrh question", "DP"];
            var Q5 = [5, "My fifth question", "FP"];    
            //etc... until Q45


            if (sessionStorage.getItem("FP") == null) {

                $("form").attr("action", "driversV2.php");
                $("#answer").hide();
                $("#start").click(function() {

                    $("#Qnum").append(1+" / 45");
                    $("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
                    $("#answer").show();
                    $("header").hide();

                    var pageType = $("#Q").attr("data-type");
                    $("input").click(function() {
                        var reponse = this.id;
                        sessionStorage.setItem(pageType, reponse);
                        localStorage.setItem("clic", 1);
                    });
                });

            } else {
                $("header").hide();
                var clicNum = parseInt(localStorage.getItem("clic"));
                var QNumber = clicNum + 1;
                var arrayCharge = [];
                for (var i = 2; i <= 45; i++) {
                  arrayCharge.push(i);
                }
                const randomQ = arrayChargeNew;
                const random = Math.floor(Math.random() * randomQ.length);
                console.log('valeur random new = '+randomQ[random]);
                var QCharge = "Q" + randomQ[random];
                var Charge = eval(QCharge);
                localStorage.setItem("random",randomQ[random]);
   
                $("#Qnum").append(QNumber+" / 45");
                $("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
                //création de la variable du type de question
                var pageType = $("#Q").attr("data-type");
                //alert(sessionStorage.getItem(pageType));
                if (localStorage.getItem("clic") < 44) {

                    $("form").attr("action", "driversV2.php");

                    if (sessionStorage.getItem(pageType) != null) {
                        var x = parseInt(sessionStorage.getItem(pageType));
                        $("input").click(function() {
                            var reponse = parseInt(this.id);
                            var addition = reponse + x;
                            sessionStorage.setItem(pageType, addition);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);
                        });
                    } else {
                        $("input").click(function() {
                            var reponse = this.id;
                            sessionStorage.setItem(pageType, reponse);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    }
                } else {
                    $("form").attr("action", "driversResultat.php");

                    if (sessionStorage.getItem(pageType) != null) {
                        var x = parseInt(sessionStorage.getItem(pageType));
                        $("input").click(function() {
                            var reponse = parseInt(this.id);
                            var addition = reponse + x;
                            sessionStorage.setItem(pageType, addition);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    } else {
                        $("input").click(function() {
                            var reponse = this.id;
                            sessionStorage.setItem(pageType, reponse);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    }
                }
            }
        });
        </script>
</body>

</html>

2 Answers

Nicolas, this is the sort of thing you should end up with:

// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;

// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
  availableQuestions.length = 0;
  for (let i = 1; i <= 10; i++) {
    availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
  }
}

// Pick a random question and display that to the user
function getRandomQuestion() {
  let osQuestions = availableQuestions.length;
  let qnElement = document.getElementById("questionnumber");
  let qElement = document.getElementById("question");
  let sButton = document.getElementById("submit");
  let rButton = document.getElementById("restart");
  // If there are no more questions, stop
  if (osQuestions == 0) {
    qnElement.innerHTML = "Finished!";
    qElement.innerHTML = "";
    sButton.style.display = "none";
    rButton.style.display = "inline";
  } else {
    // display a sequential question number rather than the actual question number
    counter++;
    rnd = getRandomNumber(0, osQuestions - 1);
    let thisQuestion = availableQuestions[rnd];
    qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
    qElement.innerHTML = thisQuestion.question;
  }
}

// Process the user's answer and remove the question from the array
function submitAnswer() {
  // ALSO Add in what needs to be done to update backend database etc when the user clicks submit
  availableQuestions.splice(rnd, 1);
  getRandomQuestion();
}

// Reset everything - for testing purposes only
function restart() {
  let qnElement = document.getElementById("questionnumber");
  let qElement = document.getElementById("question");
  let sButton = document.getElementById("submit");
  let rButton = document.getElementById("restart");
  qnElement.innerHTML = "";
  qElement.innerHTML = "";
  sButton.style.display = "inline";
  rButton.style.display = "none";
  // Reset the displayed question number counter
  counter = 0;
  createQuestions();
  getRandomQuestion();
}

// Needed to populate the array and display the first question
function runsetup() {
  createQuestions();
  getRandomQuestion();
}

window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>

<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>

I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working

Correct answer by ATD on December 27, 2020

Nicolas, this is what I think you should be doing:

// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
  arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}

// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);

// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)

// Present the question to the user on the page
// The user completes question and clicks "Submit"

// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Answered by ATD on December 27, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP