Reputation: 1
I have a quiz and want to randomize the data coming from my jSON file so that every time someone attempt the quiz sees different question order.
I came across this example but couldn't make it work out with the array comming from my jSON file. See the JS bellow:
.controller('QuizController', ['$scope', '$http', function($scope, $http, $state){
$scope.score = 0;
$scope.activeQuestion = -1;
$scope.activeQuestionAnswered = 0;
$scope.percentage= 0;
$http.get('js/quiz_data.json').then(function(quizData){
$scope.myQuestions = quizData.data;
$scope.totalQuestions = $scope.myQuestions.length;
});
$scope.randomSort = function(myQuestion) {
return Math.random();
};
HTML:
ng-repeat="myQuestion in myQuestions|orderBy:randomSort">
It would be nice if the answers were in random order also... Thanks in advance!
Upvotes: 0
Views: 1410
Reputation: 177
This might be helpful How to randomize (shuffle) a JavaScript array?
You can use the same concept on a JSON Object
EDIT
function createobj() {
var obj = [
{"Question":"This is the first question","Answer":"This is the first Answer"},
{"Question":"This is the second question","Answer":"This is the second Answer"},
{"Question":"This is the third question","Answer":"This is the third Answer"},
{"Question":"This is the forth question","Answer":"This is the forth Answer"},
{"Question":"This is the fifth question","Answer":"This is the fifth Answer"},
];
//Assigning the obj to the new one
obj = randomize(obj);
}
function randomize (obj) {
var index;
var temp;
for (var i = obj.length - 1; i > 0; i--) {
//get random number
index = Math.floor((Math.random() * i));
//swapping
temp = obj[index];
obj[index] = obj[i];
obj[i] = temp;
}
//Prints the results into the console
for (i = 0; i < obj.length; i++) {
console.log(obj[i].Question + ": " + obj[i].Answer);
}
//My edit to pass the obj back to the function
return obj;
}
Here is the function, it takes a simple JSON object i created and randomizes it. It will print the results into the Console. Hope this helps more.
Upvotes: 1