I am in the process of creating a quiz using the survey js library. For this quiz I have a bank of questions that I'd like to randomly select from.
To do this, I have stored JSON objects - serialized to JSON questions. Here is the working sample - https://plnkr.co/edit/gnL4gv75uowDPyEU
Now, this works for adding every question to the page by utilizing a foreach loop. Instead, I'd like to randomly add just 2 of the questions out of the 4.
Conceptually I understand how to do this but I am relatively new to programming.
Here is my thought process for what needs to be done:
- Get random number using the Fisher-Yates shuffle:
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranNums = shuffle([1,2,3,4]);
- Add the question from JSON at the serialized random number to the page. Repeat this twice to add two questions.
This seems relatively simple but when I go to implement it I can't seem to figure out how to actually serialize the json. In addition, even once I figure out how to serialize the json questions and select it accordingly, I don't understand the necessary syntax to add the question. Can someone please help with this?