I got the nested options Array inside of the Questionlist Array of Objects, i need a way whenever i load the component for these Arrays to be shuffled , appreciate the help.
Are you trying to rearrange the questions, rearrange the answers within the questions, or both?
If you sort an array of objects, the contents of each object travels with it. If you want to shuffle the arrays of answers within each question, make your shuffle function abstract enough to sort any array, then loop over the questions and shuffle the answers for each one.
This is the theory, an outline of what it sounds like you want. Does this help, or are you looking more for a how it’s done?
Yes thats exactly what im looking for , since this is for multi choice quiz app , its important that the correct answer position should be dynamic , i will appreciate it if you show me how it can be done.
You have an array of object, of each object you want to take a field, and apply your custom logic.
This kind of data manipulation is something you should get used to, so I encourage you to try to come up with a solution yourselves.
And if you have doubts just ask for guidance/help.
But if you really can’t here’s how I’d do it using array.map.
As I’d said, i might separate out that sort function, so you can use it anywhere. If you do that, later on you can change it out for a different one at any time.
I might do this:
// we can use this anywhere!
const shuffle = () => 0.5 - Math.random();
const testQuestions = QuestionsList.map(q => ({
...q,
// this one shuffles the answers...
options: q.options.sort(shuffle)
}))
// ...and this one shuffles the questions.
.sort(shuffle)
The solution is very similar to the one @Marmiz showed, but by pulling the shuffle function out, we gain flexibility.
Is this for the FCC curriculum? I ask, because some of our course lessons might be useful in understanding things like this.
@Marmiz@snowmonkey
i had to copy the copy the Array then apply the shuffle function which worked perfectly thanks for both of you . @snowmonkey is not for the FCC curriculum , just practicing what i learned ,.