mercredi 24 février 2016

Randomizing (shuffling) JSON Object in JavaScript

I initially used the information from prior questions to figure out how to randomize data using information I found in a Stack Overflow Q&A. (How to randomize (shuffle) a JavaScript array?) In my original attempt, I did separate randomizations for girls' names and boys' names.

npcGirls = ["Amanda", "Deja", "Grace", "Hailey","Jada", "Kylie", "Maria", "Shanice", "Victoria"];
shuffle(npcGirls);

npcBoys = ["Aiden", "Benjamin", "Daniel", "Isaiah", "Jamal", "Maurice", "Steven", "Tyrone", "Zach"];
shuffle(npcGirls);

Randomization was completeed using the Fisher-Yates algorithm submitted by gnarf.

function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}

As I've thought about it and read more, I realize that I really need to use a JSON instead of a simple array. JSON is new to me. I've figured out how to set it up:

var npc = [
{"npcName":"Amanda", "npcSex":"girl", "npcRisk":"1"},
{"npcName":"Deja", "npcSex":"girl", "npcRisk":"2"},
{"npcName":"Grace", "npcSex":"girl", "npcRisk":"3"},
{"npcName":"Hailey", "npcSex":"girl", "npcRisk":"4"},
{"npcName":"Jada", "npcSex":"girl", "npcRisk":"5"},
{"npcName":"Kylie", "npcSex":"girl", "npcRisk":"6"},
{"npcName":"Maria", "npcSex":"girl", "npcRisk":"7"},
{"npcName":"Shanice", "npcSex":"girl", "npcRisk":"8"},
{"npcName":"Victoria", "npcSex":"girl", "npcRisk":"9"},
{"npcName":"Aiden", "npcSex":"boy", "npcRisk":"1"},
{"npcName":"Benjamin", "npcSex":"boy", "npcRisk":"2"},
{"npcName":"Daniel", "npcSex":"boy", "npcRisk":"3"},
{"npcName":"Isaiah", "npcSex":"boy", "npcRisk":"4"},
{"npcName":"Jamal", "npcSex":"boy", "npcRisk":"5"},
{"npcName":"Maurice", "npcSex":"boy", "npcRisk":"6"},
{"npcName":"Steven", "npcSex":"boy", "npcRisk":"7"},
{"npcName":"Tyrone", "npcSex":"boy", "npcRisk":"8"},
{"npcName":"Zach", "npcSex":"boy", "npcRisk":"9"}];

I haven't figured out how to call the function correctly or how to do separate randomizations for girls and boys. So, for example, the end of the randomization should replace girls' names with other girls' names but keep npcRisk in the same order. Guidance would be appreciated.




Aucun commentaire:

Enregistrer un commentaire