Tips for shuffling questions within arrays

var quiz = [
        {
            "question"      :   "Q1: What is the greatest invention of all time?",
            "choices"       :   [
                                    "Wheel",
                                    "Electricity",
                                    "Internet",
                                    "Printing Press"
                                ],
            "correct"       :   "Internet",
            "explanation"   :   "The Internet revolutionized communication and access to information.",
        },
        {
            "question"      :   "Q2: Who is the most influential leader in history?",
            "choices"       :   [
                                    "Gandhi",
                                    "Napoleon",
                                    "Martin Luther King Jr.",
                                    "Alexander the Great"
                                ],
            "correct"       :   "Gandhi",
            "explanation"   :   "Gandhi's nonviolent approach inspired movements worldwide.",
        },
        {
            "question"      :   "Q3: Which animal is considered a symbol of wisdom?",
            "choices"       :   [
                                    "Elephant",
                                    "Owl",
                                    "Dolphin",
                                    "Fox"
                                ],
            "correct"       :   "Owl",
            "explanation"   :   "Owls are associated with wisdom in many cultures.",
        },

    ];

function loadQuestion(){

        //set temporary variable for creating radio buttons
        var radioButton;

        //clear out radio buttons from previous question
        document.getElementById('content').innerHTML = "";

        //loop through choices, and create radio buttons
        for(var i=0; i < quiz[currentQuestion]["choices"].length; i++){

            radioButton  = document.createElement('input');
            radioButton.type = 'radio';
            radioButton.name = 'quiz';
            radioButton.id = 'choice'+ (i+1);
            radioButton.value = quiz[currentQuestion]["choices"][i];

            //create label tag, which hold the actual text of the choices
            var label = document.createElement('label');
            label.setAttribute('for','choice'+ (i+1));
            label.innerHTML = quiz[currentQuestion]["choices"][i];

            //create a <br> tag to separate options
            var br = document.createElement('br');

            //attach them to content. Attach br tag, then label, then radio button
            document.getElementById('content').insertBefore(br);
            document.getElementById('content').insertBefore(label, br);
            document.getElementById('content').insertBefore(radioButton, label);
        }

Answer №1

let randomIndex = Math.floor(Math.random() * yourArray.length);

Answer №3

Here's a snippet that loops through all the quiz items and utilizes the "How to randomize (shuffle) a JavaScript array" method to shuffle the choices within the array:

var quiz = [{"question": "Q1: Who is the best scientist?","choices" : ["Sir Isaac Newton","Albert Einstein","Nicolaus Copernicus","Ralph Waldo Emmerson"],"correct" : "Albert Einstein","explanation" : "Albert Einstein drafted the special theory of relativity.",},{"question": "Q2: Who looks better?","choices" : ["Thomas","Dwight Howard","Benjamin Parker","Jeremy Lincoln"],"correct" : "Benjamin Parker","explanation" : "He has better features to start with",},{"question": "Q3: What event began on December 25, 1990?","choices" : ["Christmas","Chinese NewYear","American Civil War began","Declaration of Independence"],"correct" : "Christmas","explanation" : "Duh, Christmas? I think this needs no future explaination"}],
    shuffleArray = function (array) {
      for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1)),
            temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    },
    loadQuestions = function (quiz) {
      quiz.forEach(function(item) {
        var choices = shuffleArray(item.choices);
        console.log(item.question);
        choices.forEach(function(choice) {
          console.log('-', choice);
        });
      });
    }
;

// Loading and shuffling questions
loadQuestions(quiz);

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

What is the most effective method for starting an application from a web browser, regardless of platform or browser used?

Forgive me if this question has been asked before in a similar way. I have multiple test applications that operate on different platforms such as Windows 95, Windows XP, SUSE, RedHat, and other variations of UNIX. Currently, the process involves a native a ...

Utilizing jQuery to target a select element's two specific children

I am trying to target the parent element by matching two specific children elements. Here is my code: $('span:contains("11:00am"), span.name:contains("Tom")').parents("a").css("background-color","rgb(255, 255, 255)"); <script src="https://c ...

Conceal any DIVs that do not include every specified class

My webpage consists of numerous DIVs, each representing a specific product with its own set of characteristics. I have assigned these characteristics as classes to each product. Here is an example of how each product DIV is structured: <div class=&apos ...

I can't seem to figure out why my characters keep disappearing from the HTML string when I attempt to dynamically add HTML using JavaScript

I am currently facing an issue with dynamically adding links to a page. The links are being added successfully, however, the '[' and ']' at the beginning and end of the line are disappearing. Here is the code snippet from my .js file: ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...

Sorting a two-dimensional array of strings using Quicksort in the C programming language

I am troubleshooting my implementation of the quick sort algorithm for sorting strings in a 2D array. While it works for most cases, I'm encountering an issue with a specific scenario. Despite researching similar problems on platforms like Stack Overf ...

Dispose the inputpicker filter after setting the value

I am currently utilizing the "Jquery inputpicker plugin" for creating dropdown menus. More information about this plugin can be found here. To initialize my dropdown, I use the following code: $('#test').inputpicker({ data:[ {value:"1 ...

Are you struggling with Grails - Ajax submission not functioning properly?

Trying to update a div when a form is submitted, but it seems like something is missing. Here's the HTML code: <%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <meta name="layout" content="main" /> ...

I'm feeling a bit lost trying to figure out how to write insert statements using knex

I'm struggling with a specific issue related to the Knex.JS implementation that I just can't seem to figure out. It's not directly related to PostgreSQL, but more about how Knex is handling my data. The code snippet below works fine for ins ...

Tooltip positioned within a custom container using Material UI

Currently, as part of my Chrome extension development utilizing React and Material UI, I am implementing an inject page strategy. I have managed to set up a tooltip for the Fab button, but unfortunately, it appears outside the DOM of my extension. Upon ins ...

The class java.util.Arrays$ArrayList is unable to be converted into java.util.ArrayList within a Parcelable object

These are the classes that I have written: public class Company implements Parcelable { private int uid; @SerializedName("field_user_org_name_value") private String name; @SerializedName("field_user_org_address_value") private String address; @Serialized ...

Is it possible to gradually open or close a div element?

Looking for a way to add an effect to the code below that opens/closes a div on mouseover above an image. Any examples or suggestions? I'm not exactly a javascript expert. HTML: <div> <div class="under"><img src="http://oi60.tinypic.c ...

Array of strings containing time information

I am trying to come up with a solution that generates numbers ranging from 13:35 to 14:31. Currently, my method just prints out the numbers using Console.WriteLine. Console.WriteLine I am thinking if it is possible to save these numbers into an array l ...

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Using a sequence of array methods like filter, map, and reduce in succession instead of relying on a double loop

Having encountered a perplexing issue that I can't seem to comprehend... here is what I am attempting to achieve. Presented with the following array of objects, products = [ { name: 'Sonoma', ingredients: ['artichoke', 's ...

Expanding Images Using HTML and CSS

I am currently working on a memory card game using HTML, CSS, and JS as part of my practice. You can check out what I have accomplished so far right here: . Upon inspection, you may notice that the images of the question mark and the flipped card are sligh ...

Difficulty with BCRYPT retrieving information from MySQL

As a beginner in programming, I've hit a roadblock and can't seem to find any solutions. I've managed to successfully register users into my database and hash their passwords. Now, I'm trying to implement a login feature for these users ...

What is preventing me from accessing session data using nuxtServerInit?

When attempting to retrieve sessions, I encounter an issue. Is everything set up correctly in the following main files: server, config? store/index.js export const actions = { nuxtServerInit ({ commit }, { req }) { console.log(req); } The console log ...