Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to shuffle JSON.parse data?

Is it possible to shuffle a json parsed result from ajax?

$.ajax({
    method: 'GET',
    url: '/-pathSomething-/--ExampleOnly--',
    data: { sample: sample, sample: sample, sample: sample },
    success: function (result) {
        var ExamDislayQNChoiceML = JSON.parse(result);
    }
});

it is looks like this here

i don’t know how to do it so i don’t have much code to show..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

expected output.
randomly

{ QuesNo: 3, QuesID: 3, ... }
{ QuesNo: 1, QuesID: 1, ... }
{ QuesNo: 4, QuesID: 4, ... }
{ QuesNo: 2, QuesID: 2, ... }
{ QuesNo: 5, QuesID: 5, ... }

>Solution :

use the Fisher-Yates shuffle algorithm here is a documentation link: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle and Here’s an example of how use it to shuffle the array of objects

$.ajax({
    method: 'GET',
    url: '/-pathSomething-/--ExampleOnly--',
    data: { sample: sample, sample: sample, sample: sample },
    success: function (result) {
        var ExamDislayQNChoiceML = JSON.parse(result);
        shuffleArray(ExamDislayQNChoiceML);
        console.log(ExamDislayQNChoiceML); // shuffled array
    }
});

function shuffleArray(array) {
    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]];
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading