Verify the existence of an array element and proceed to the next one in JavaScript if it does not

I am attempting to select 3 random answers from an array of possible answers and store them in a new array. The new array, selectedAnswers, should contain 3 random answers along with the correctAnswer. While I have made some progress, I am facing an issue where I am unable to skip already used array elements and end up with duplicates in my new array.

You can view the code here.

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];
var randomNumber = 0;

function randomAnswer() {
    if (selectedAnswers.length < 4) {
        randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

        for (i = 0; i < answerList.length; i++) {
            if (answerList[randomNumber] === answerList[i]) {
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

                randomAnswer();

            } else {
                selectedAnswers.push(answerList[i]);
                console.log(selectedAnswers);
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;
                randomAnswer();
                break;
            }
        }
    }
}

randomAnswer();

Answer №1

If you're looking for a more efficient way to randomize your array, I would recommend using a shuffle function instead of constantly selecting random indexes.

Keep in mind that this method assumes that the maximumAnswers value will always be less than or equal to the length of answerList plus one.

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [];
var maximumAnswers = 4;

function generateAnswers() {
    var tempAnswerList = shuffle(answerList.slice()); // Make a copy of the answerList and shuffle it
    tempAnswerList = tempAnswerList.slice(0, maximumAnswers - 1); // Subtract 1 because we will add the correct answer
    tempAnswerList.push(correctAnswer); // Add the correct answer
    tempAnswerList = shuffle(tempAnswerList); // Shuffle again to randomize the correct answer's position
    console.log(tempAnswerList);
}

// Shuffle function source: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
function shuffle(o) { 
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

generateAnswers();

JSFIDDLE DEMO

Answer №2

I made some updates to your code because I am unsure about the necessity of using a large recursive function like the one you had:

var answerList = ["answer 1","answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];

function incorrectAnswers(answerList, number = 3) {
    //number represents the desired number of answers to be returned, with a default set to 3
    var wrongAnswers = [];
    //While the wrongAnswers array is not yet filled properly:
    while (wrongAnswers.length < number && answerList.length > number) {
        //Generate a random value
        var random = Math.floor(Math.random() * answerList.length);
        //Add it to the array if it is not already included (using indexOf)
        if (wrongAnswers.indexOf(answerList[random]) == -1) 
             wrongAnswers.push(answerList[random]);
    }
    //If the list of potential answers is shorter than the desired number, return all possible answers; otherwise return the generated list
    if (answerList.length <= number) 
        return answerList; 
    else 
        return wrongAnswers;
}

console.log(incorrectAnswers(answerList));

Check it out on Fiddle: http://jsfiddle.net/oybojgzm/2/

Answer №3

/*
    This function selects a specified number of random answers from a pool of possible answers and pushes them into a selected answers array.
*/
function selectRandomFromAndPushInto(count, answerPool, selectedAnswers) {
    //Create a copy of the answerPool to avoid modifying the original array
    answerPool = answerPool.slice();

    //Iterate 'count' times to select random answers
    for(var iteration = 0; iteration < count; iteration ++) {
        //Generate a random index within the range of the answerPool array
        var index = Math.round(Math.random() * (answerPool.length - 1));
        //Push the selected answer into the selectedAnswers array
        selectedAnswers.push(answerPool[index]);
        //Remove the selected answer from the answerPool to prevent duplicates
        answerPool.splice(index, 1);
    }

    //Return the selected answers array
    return selectedAnswers;
}

var answerPool = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var selectedAnswers = ["CORRECT!"];
console.log(selectRandomFromAndPushInto(3, answerPool, selectedAnswers));

Output may resemble the following when tested with node.js:

[ 'CORRECT!', 'answer 3', 'answer 5', 'answer 4' ]

Answer №4

To put it simply:

const choices = ["choice A", "choice B", "choice C", "choice D", "choice E"];
const correctChoice = "RIGHT!";
const chosenChoices = [correctChoice];
let randomIndex = 0;

function randomChoice() {
while(chosenChoices.length < 4){
    randomIndex = Math.floor(Math.random() * choices.length);
    if(!(chosenChoices.indexOf(choices[randomIndex])>-1))
        chosenChoices.push(choices[randomIndex]);
    }
}

randomChoice();

http://jsfiddle.net/oybojgzm/5/

Answer №5

One effective strategy is to initialize an array for testing purposes:

 var optionList = ["option A", "option B", "option C", "option D", "option E"];
 var correctOption = "CORRECT!";
 var chosenOptions = [];
 var randomNum, temp, temp2, length, index;

 function generateRandomOption() {
   temp=[];
   temp2=0; //number of elements currently in the temp array
   length=optionList.length; //store length value for efficiency
   while(temp2<3) { //continue loop until 3 numbers are in the temp array
     randomNum = Math.floor(Math.random() * length); //random index within range
     for(index=0; index<temp2; index++) //initial random number is always valid
       if(temp[index]==randomNum) //if index already exists in temp array
         break; //stop loop to avoid index matching temp2
     if(index==temp2) //true after the loop ends without breaking
       temp[temp2++]=randomNum; //store different indices in temp array
   }//end of while loop, obtaining 3 different random numbers
   //randomly insert the correct answer into the final array
   randomNum = Math.floor(Math.random() * 3); //index values from 0 to 2
   for(index=0; index<3; index++) {  //3 indices in the temp array
     if(index==randomNum) //if the position matches the random index for the answer
       chosenOptions.push(correctOption);  //place the correct answer in the output
     chosenOptions.push(optionList[temp[index]]); //add another answer to the output
   }
   console.log(chosenOptions);
 }

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

retrieve all entries from a paginated grid

Currently, I am utilizing the datatable feature in bootstrap4 with a table that has pagination set to display 10 items per page. I have implemented a function to retrieve values from the table, however I am facing an issue where I am only able to retriev ...

Transitioning to offline mode with cypress resulted in a promise that remained unresolved

Can anyone assist me with following the official guidelines from Cypress on how to enter offline mode? Encountered an error => The callback function returned a promise that never resolved. Here is the callback function in question: () => { ret ...

Retrieving data arrays from response.json

I've been on a wild goose chase trying to solve this puzzling issue. RAWG has transitioned to using their own API instead of Rapid API for game reviews, and I'm in need of data for "Tom Clancy Rainbow Six Siege". Despite my efforts to convert t ...

Logging out of Laravel after sending a POST request

I'm developing a laravel application that heavily relies on POST requests. One common type of request in my app looks like this: var classElements = document.querySelectorAll("tr.ui-selected td.filename"); var csrf = $('input[name=_token]') ...

Having trouble with npm start and install - not functioning as expected

https://i.sstatic.net/PnmzJ.png I attempted to execute npm install and npm start commands, but unfortunately, neither of them is functioning. I even went ahead and reinstalled nodejs, but the issue persists. Can anyone suggest a solution to this problem? ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

What could be causing the error when attempting to send an HttpResponse from a Django View function?

Trying to utilize Ajax, I'm attempting to call a Django View function from JavaScript code. The View function is expected to return an HttpResponse, which should then be printed out on the console. However, upon inspection of the console, it simply s ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

What is the process for sending a post request with a JSON payload to an external API using Node.js?

I am currently facing an issue while attempting to send a POST request with a JSON payload to an external API using node.js. Below is the code I am using: var express = require('express'); var bodyParser = require('body-parser'); var ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Is there a way to receive a string of variable length using getchar without prompting the user for the string size beforehand?

I am struggling to collect user input using only getchar() and malloc() to store it in a string of unknown size. Although I have done this successfully before, I seem to have forgotten the correct method. Currently, I am facing an issue where my function i ...

In order to ensure functionality on Firefox 3 and Opera, it is essential to include multiple <script> tags and the <!-- //required for FF3 and

I have utilized Spring Roo to create a basic web project. The user interface is JSP-based with a Tiles layout. Upon examining the default layout code, I noticed that the script tags were defined as: <script src="${dojo_url}" type="text/javascript" > ...

What is the best way to import my json information into an HTML table and customize the rows as radio buttons using only Javascript?

I am facing an issue with processing a JSON response: var jsondata = dojo.fromJson(response); There is also a string that I am working with: var jsonString = jsondata.items; The variable jsonString represents the JSON data in the file: jsonString="[ ...

The functionality of transparent code on Three.js appears to be not functioning properly

I have researched and attempted various solutions, but unfortunately none of them have been successful. Here is an example of what I have tried: var renderer = new THREE.WebGLRenderer( { alpha: true } ); and root.renderer.setClearColor(0xffffff,0); De ...

Vue Component Update DisorderI hope this meets your expectations

Below is my code using Bootstrap, Vue, and Axios: SETUP: *Please disregard the tab-contents in component_a main.js Vue.component('component_a', { props: ['info'], template: `<div> // Component A template code here } ...

Unable to iterate through elements of a string array using PowerShell

Having trouble looping through items using PowerShell with the code below. $ipAddress = @('107.20.253.26', '107.20.178.220', '8.8.8.8') for($i=0; $i -le $ipAddress.count; $i++) { $resolve = nslookup $i | Format-list ...

A guide on extracting text content exclusively from Markdown files using Javascript

I've been working on a blogging platform with Vue that serves Markdown (*.md) files for posts. My goal is to display a list of published posts on the main page along with a preview of the first 30 words of each post. Currently, I have a function that ...

Ensure that every route is prefixed with /api

Is there a way to set all routes accepted by Express to start with /api without explicitly defining it? Current: this.app.get('/api/endpoint-A', (req, res) => { return res.send('A'); }); this.app.get('/api/endpoint-B', ...

Iterate through a jQuery function to retrieve values from checkboxes starting from the 4th one that has been clicked

I am currently using a loop in a form to calculate the total price of a product based on user selections. However, I have encountered a challenging task where certain checkbox groups have specific rules. For instance, group A should only contribute to the ...