I have an array of questions that I want to randomize and put into a quiz. However currently it can choose the same question twice and put it in the quiz twice. If I want to delete the question after it has been pushed to a new array, without knowing its index how can I remove it?
My code that i tried was this
var index = questionsArrayCopy.findIndex(function(item, i){return item.question === randomQuestion});
questionsArrayCopy.splice(index)
But it didn't work and I had no errors
My current code is below:
const myQuestions = [
{
question: 'What is 37 x 89?',
answers: [
{ text: '6989', correct: false },
{ text: '3293', correct: true },
{ text: '2400', correct: false },
{ text: '9870', correct: false }
]
},
{
question: 'What year is the great fire of london?',
answers: [
{ text: '1666', correct: true },
{ text: '1888', correct: false },
{ text: '1600', correct: false },
{ text: '1566', correct: false }
]
},
{
question: 'Is web development fun?',
answers: [
{ text: 'Kinda', correct: false },
{ text: 'YES!!!', correct: true },
{ text: 'Um no', correct: false },
{ text: 'IDK', correct: false }
]
},
{
question: 'What is 4 * 2?',
answers: [
{ text: '6', correct: false },
{ text: '8', correct: true }
]
},
]
function getRandomNumberBetween(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const GetRandomQuestionFromArray = (array) => {
const randomIndex = getRandomNumberBetween(0, array.length);
return array[randomIndex];
}
const GetRandomQuestionsArray = (howManyQuestions) => {
const questionsArrayCopy = [...myQuestions];
const finalQuestionArray = [];
for (let i = 0; i < howManyQuestions; i++) {
const randomQuestion = GetRandomQuestionFromArray(questionsArrayCopy);
finalQuestionArray.push(randomQuestion);
}
return finalQuestionArray;
}
const questions = GetRandomQuestionsArray(3);
console.log(questions)
If I want to stop duplicate questions from entering the final array(questions) and just choose random ones from the other array(myQuestions) how would I do that?