A
A
Alexander2021-07-16 20:44:20
JavaScript
Alexander, 2021-07-16 20:44:20

How to randomly shuffle a 2D array in JS?

Hello. I am practicing using JS by doing small tests. I have an array of this type:

const questions = 
[
    {
        question: "Какой-то вопрос",
        answers:
        [
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: false},
            {text: "Ответ", correct: true}
        ]
    },

   {
        question: "Какой-то вопрос",
        answers:
        [
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: false},
            {text: "Ответ", correct: true}
        ]
    },

{
        question: "Какой-то вопрос",
        answers:
        [
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: true},
            {text: "Ответ", correct: false},
            {text: "Ответ", correct: true}
        ]
    },
]


On the Internet, I found a code that shuffles the elements (that is, internal arrays) of the questions array (I wrote let shuffledQuestions before that):

shuffledQuestions = questions.sort(() => Math.random() - .5);


And how to shuffle the answers (answers), so that the answers are placed in random order?

Please advise, I will be grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Prog Spectar, 2021-07-16
@AlexB_49

console.log(JSON.stringify(questions));
questions.forEach((e) => {
return e.answers.sort(() => Math.random() - 0.5);
});
console.log(JSON.stringify(questions));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question