I'm making an quiz app in react. Everything is working perfectly exept from a function that shuffles my array so the answers seem random every time. Here's the code.
shuffleArray() {
let array = this.state.answerArray;
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
Fetching and storing is working, but anytime I call that shuffleArray function, my original array (answerArray) also shuffles exactly like shuffledArray.
Im calling function after setState after fetching my data
this.setState(
{
qid: _id,
question: question,
correct_answer: correct_answer,
answerArray: [
correct_answer,
answer1 || " ",
answer2 || " ",
answer3 || " "
]
},
() => {
this.setState({
shuffledArray: this.shuffleArray()
});
}
);
Any idea why do both arrays shuffle?