Acquiring information by using values from a different array

Currently, I am in the process of developing a page that generates random sets of questions along with their corresponding answers. Unfortunately, I am facing a challenge in matching the questions with their respective answers.

For the questions, I have created an array called 'myWords', and for the answers, another array called 'myAnswers':

//Array for Questions
var myWords = [
    'Test1',
    'Test2',
    'Test3',
    'Test4',
    'Test5',
    'Test6',
    'Test7',
    'Test8',
    'Test9',
    'Test10',
    'Test11',
    'Test12',
    'Test13',
    'Test14',
    'Test15'
]

//Array for Answers
var myAnswers = [
    'Answer1',
    'Answer2',
    'Answer3',
    'Answer4',
    'Answer5',
    'Answer6',
    'Answer7',
    'Answer8',
    'Answer9',
    'Answer10',
    'Answer11',
    'Answer12',
    'Answer13',
    'Answer14',
    'Answer15'
]

With this setup, I am using the following script to randomly select 10 unique questions from the 'myWords' array:

    //randomly pick 10 words
    while(selectWords.length < 10){
        var randomWord = myWords[Math.floor(Math.random() * myWords.length)]
        if(selectWords.indexOf(randomWord) > -1) continue;
        selectWords[selectWords.length] = randomWord;
    }

Now, the challenge I am facing is how to map each question to its corresponding answer in the 'myAnswers' array. The desired output should be presented in a table format like this:

Question 1 | Answer 1

I appreciate any help with this task. Thank you!

Answer №1

Store questions and answers in a single array with objects:

const QAArray = [
    { query: "Question1", response: "Answer1" },
    { query: "Question2", response: "Answer2" },
    ...
];

By adding these objects to your QAList array, you can easily access the .query and .response properties as needed.

Answer №2

It is more efficient to pair questions with answers directly, but if you are constrained by the given input, you can also use the map method to combine them. This way, when selecting a random question, you will also have access to its corresponding answer.

var myWords=['Test1','Test2','Test3','Test4','Test5','Test6','Test7','Test8','Test9','Test10','Test11','Test12','Test13','Test14','Test15'];
var myAnswers=['Answer1','Answer2','Answer3','Answer4','Answer5','Answer6','Answer7','Answer8','Answer9','Answer10','Answer11','Answer12','Answer13','Answer14','Answer15'];

const questionsAndAnswers = myWords.map((question, i) => ({ question, answer: myAnswers[i] }));
const selectWords = Array.from({ length: 10 }, () => (
  questionsAndAnswers.splice(Math.floor(Math.random() * questionsAndAnswers.length), 1)[0]
));
console.log(selectWords);

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

Encountering a 404 error while using Angular HTML5Mode setting

I recently enabled pretty URLs in my Angular application by switching to html5mode. However, whenever I try to refresh the page, I encounter a 404 error. For instance, if I access my app through , everything functions as expected. But when I attempt to r ...

jQuery SlideUp and SlideDown causing Margin Bug in Internet Explorer 7

When clicking the "more info" or "less info" buttons to slide content up or down, a spacing glitch is created in IE7. Using show/hide instead of slideUp/slideDown seems to solve the issue. Is there a way to make sliding work in IE7 without causing this pro ...

Unable to retrieve valid inputs from text fields by utilizing jQuery selectors

Extracting information from text fields is my goal. Specifically, these fields contain dates which consist of three parts: the year, month, and day. The dates are divided into two sections - the first date and the last date, serving as boundaries for a sea ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

When the server reloads, an error occurs stating 'CodeMirror' is not defined when using CodeMirror with Vuejs/Nuxtjs

I've integrated CodeMirror into one of the textarea elements in my Nuxtjs/Vuejs application. I want to format the textarea to resemble XML. While the CodeMirror functions correctly at times, I encounter an error when reloading the page: Test.vue 33:1 ...

Ensuring the correct range with HTML TextBoxFor

Is there a way to validate user input in a TextBoxFor to ensure it is less than a certain number at run-time? Here is the current code snippet for reference - <div class="col-md-3 input-group"> <span class="input-group-addon ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

Customizing Form Inputs in ReactJS using Props Array

Trying to wrap my head around handling a dynamic number of props data for a form. Despite searching high and low on Google, I've come up empty-handed. I am gathering data on the number of appointments based on the number of dogs owned by a user. So, t ...

I'm curious about the time complexity of a nested for loop when the inner loop iterates through a separate array

Is it possible to only consider the time complexity of one array while disregarding another array in our calculation? For example, when looking at the growth of the outer array, can we simply say O(N) instead of O(N*M)? for (int i = 0; i <= n.size(); ...

How can you generate a Base64 string with Node.js?

I recently utilized the html2pdf npm package to generate a base64 string of a PDF file and then sent it to my Node.js server. I used Nodemailer to send this PDF as an email attachment by configuring the mailOptions object like so: let mailOptions ...

Unable to retrieve the value property from document.getElementById as it is null

Can someone help me with reading the input field value in my code? <input type="text" name="acadp_fields[1200]" class="text" placeholder="" value="December 26, 1969"> Here is the code snippet I am us ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

How to implement Google Tag Manager using the next/script component in Next.js 11?

Version 11 of Next.js recently introduced a new approach with the Script component offering various strategies. To avoid duplicate tags, it is advised to implement Google TagManager using the afterInteractive strategy. In my experimentation: // _app.js ...

No need to conceal content when switching to another tab if the tab is set to stay in place

My current setup involves using material UI and react-sticky, which has been functioning well. However, I have encountered an issue that I am seeking help with. Here is a link to what I have tried so far. Below are the steps to reproduce this issue: S ...

Trigger jQuery when a breakpoint has been met

I am working on a responsive design that has multiple breakpoints. Within the content, some block dimensions are calculated using jQuery. Whenever the viewport changes, these dimensions also change and therefore the calculation needs to be re-run. How can ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

What is the best way to instruct firebase-admin to halt during test execution?

Running process.exit() or --exit in my mocha tests doesn't feel right. I'm currently working on code that utilizes firebase-admin and while attempting to run mocha tests, wtfnode showed me: wtfnode node_modules/.bin/_mocha --compilers coffee:co ...