2

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..

expected output. randomly

{ QuesNo: 3, QuesID: 3, ... }
{ QuesNo: 1, QuesID: 1, ... }
{ QuesNo: 4, QuesID: 4, ... }
{ QuesNo: 2, QuesID: 2, ... }
{ QuesNo: 5, QuesID: 5, ... }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Strywyr
  • 242
  • 15
  • 1
    What do you mean by shuffle ? – Sudhir Ojha Feb 16 '23 at 07:11
  • 1
    Think in terms of shuffling an array. If you needed to sort object properties you could probably go about shuffling an array of object keys. For now copy and paste the text `[javascript]fisher yates` into the search box at the top of and belonging to this page and press enter. – traktor Feb 16 '23 at 07:20

3 Answers3

1

this could do your request

let myJSON = {
  "name": "John",
  "age": 30,
  "city": "New York"
};

let myArray = Object.entries(myJSON);

for (let i = myArray.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [myArray[i], myArray[j]] = [myArray[j], myArray[i]];
}

myJSON = Object.fromEntries(myArray);

console.log(myJSON);

This will be the output

{
  "city": "New York",
  "name": "John",
  "age": 30
}
Nothingbutageek
  • 357
  • 1
  • 11
1

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]];
    }
}

Rory
  • 437
  • 1
  • 13
1

Assuming that you wanted to shuffle array of questions objects: You can pass Math.random() to Array.sort() method. Math.random() returns float between 0 and 1. When you subtract 0.5 from result of Math.random(), the Array.sort() compare function returns random positive or negative value, so the array is shuffled:

const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
const shuffledArr = shuffleArray(arr);
protob
  • 3,317
  • 1
  • 8
  • 19