Choose a random element from an array and then modify the array

Can someone please assist me with this task? I am creating an array that corresponds to specific question numbers.

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

I then utilize these numbers to display the respective question, answer, and click. Afterwards, I select a new value from the array using this method:

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

This successfully loads a new question, but the array remains unchanged. I attempted the following approach:

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

Unfortunately, this did not yield the desired outcome :-(

Thank you in advance for your assistance. Nicolas

Please find below the complete code for better understanding. Apologies for missing it earlier:

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

Answer №1

Nicolas, here is an example of what the final result should look like:

// This code snippet is from my JavaScript library file
// It generates a random number within a specified range
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Define variables that need to be accessed globally
let availableQuestions = [];
let rnd = 0;
let counter = 0;

// Populate the question array with sample data
function createQuestions() {
  availableQuestions.length = 0;
  for (let i = 1; i <= 10; i++) {
    availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
  }
}

// Select a random question and display it to the user
function getRandomQuestion() {
  let totalQuestions = availableQuestions.length;
  let qnElement = document.getElementById("questionnumber");
  let qElement = document.getElementById("question");
  let sButton = document.getElementById("submit");
  let rButton = document.getElementById("restart");
  
  if (totalQuestions == 0) {
    qnElement.innerHTML = "Finished!";
    qElement.innerHTML = "";
    sButton.style.display = "none";
    rButton.style.display = "inline";
  } else {
    counter++;
    rnd = getRandomNumber(0, totalQuestions - 1);
    let thisQuestion = availableQuestions[rnd];
    qnElement.innerHTML = "Question: " + counter + " (Actual Question Number: " + thisQuestion.questionnumber + ")";
    qElement.innerHTML = thisQuestion.question;
  }
}

// Process the user's answer and remove the question from the array
function submitAnswer() {
  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";
  counter = 0;
  createQuestions();
  getRandomQuestion();
}

function setupEnvironment() {
  createQuestions();
  getRandomQuestion();
}

window.onload = setupEnvironment;
<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 added a counter variable to hide the actual question number from the user, but still display it for demonstration purposes.

Answer №2

Nicolas, here is my suggestion for what you should do:

// Begin by creating an array in any manner that suits your needs
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
  arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}

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

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

// Display the question to the user on the page
// The user answers the question and clicks "Submit"

// Next, remove the question using the SAME index number
arrayCharge.splice(rnd,1);
// Check if the array has decreased in size after removing an entry - it should now be 43
console.log(arrayCharge.length);

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

Copying a character array to a row in a table in C programming

In my current project, I am working with an array of pointers called char *nline[MAX_M]. I need to efficiently copy each element nline[i] to the ith row of a table named char TAB[MAX_M][MAX_N]. My initial attempt involved using the following loop: for (i ...

Scroll Bar Menu (User-Controlled)

I'm looking for any libraries out there that can replicate or provide a similar horizontal scrolling menu to that of espn.com's homepage. I'm relatively new to jquery and feeling a bit lost on where to begin. I did some searching on Google, ...

Exploring ways to enhance the appearance of a Sidebar Widget Navigation using JQuery

When creating navigational items with submenus, such as 'Primary Fees', I added an arrow for visual indication. To enhance user experience, I included an animation that rotates the arrow and highlights the Main Menu item in red upon hovering. Thi ...

Verify that all keys of an object are present as values in an array of objects

Imagine having two entities like the following: const obj1 = {key1: "", key2: "", key3: ""}; const array2 = [ { name: "key1", }] Is there a way to verify if array2 contains an object with the same name as ea ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

How can we modify the elements within an Object tag in HTML? If it is achievable, what is the process?

I am working on a project involving an HTML page that includes content from an external website using an HTML object tag as shown below: <object data="someUrl-on-different-domain-than-host" type="text/html"></object> My goal is to use jQuery ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

One required positional argument is needed in `update_one()`: 'update' is missing

I've exhausted all possible options, but I can't seem to make it work. Any suggestions on how I can get this code to function properly? I attempted using ajax_data to update the values, but it was unsuccessful. The main goal of this code is to al ...

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

Determine whether either of these elements has the mouse hovering over it using jQuery

In my DOM, I have two separate elements that need to change when either one is hovered over. If the link is hovered over, not only does the image src need to change (which is easy), but also the link color needs to change. Similarly, if the image is hovere ...

Foreign key is not being posted when submitting the form using Laravel and Vue

My dilemma involves managing two tables. Here is the structure of each: Table one, referred to as "parties", consists of the following fields: public function up() { Schema::create('parties', function (Blueprint $table) { $table-> ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

Is there a way to access the origin of an iframe?

I am facing a challenge with an HTML page that includes an iframe. Within the iframe, there are text and buttons that trigger onclick scripts. However, I'm having difficulty retrieving the values of getBoundingClientRect when I specify the ID of the b ...

Utilizing JQuery's serialize method to transfer form data to an ASP.NET MVC controller without the need to actually submit the form

Currently developing an ASP.NET MVC application that includes a form with multiple buttons to submit the data. One specific button needs to send the current status of the form's controls to the controller without actually submitting the whole form. My ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...