Currently if row three was randomly selected it would output an array with one entry (your object), like so:
[[object Object] {
e: "ee",
g: "gg",
h: "hh"
}]
We can just use arrays and the Fisher-Yates function, which can be found here: https://github.com/coolaj86/knuth-shuffle
This should give us a randomized array of the values.
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
If you need the keys associated with the value, just use an array of objects. Instead of using "one", "two", "three", etc to identify each set, we can just use the index of the object in the array. For example:
var list = [
{"a" : "aa", "b": "bb", "c" : "cc"},
{"d" : "dd", "e": "ee", "f" : "ff"},
{"g" : "gg", "e": "hh", "i" : "ii"},
];
Then we'd use:
shuffle(list);
console.log(list[0]);
which should give us a randomized array of objects. Each time it ran it'd get a random object:
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
a: "aa",
b: "bb",
c: "cc"
}
Just grab the first item in the array after shuffling it, list[0]
and use for-in loop to get the values:
var randomResult = list[0];
for (key in randomResult){
console.log(randomResult[key];
}
If you don't need the key associated with the value, i.e., "a" with "aa", and you just wanted to get a random selection from your values you can use an array and the Fisher-Yates (aka Knuth) Shuffle function.
For example:
var list = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
We can then apply it to the array
shuffle(list)
and we'd get an array with the same values (no repeating) that is randomized and can be iterated over.
["cc", "ee", "bb", "gg", "aa", "ff", "dd"]
If you need values to be grouped together but you don't need the keys, i.e., you need 'aa', 'bb', 'cc' to always be returned together, you can use an array of arrays AKA a multidimensional array.
var list = [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['gg', 'hh', 'ii']];
If we run the sorted function along with a little extra code we can get the three values
function sortedMulti(array){
sorted(array);
return array[0]
};
With this we'd get a random set each time.
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["gg", "hh", "ii"]
["gg", "hh", "ii"]
This would randomize the array, meaning you'd get a random set at the index 0 of the main array. You can then either return it (like I have) or iterate through the items in the array with a for loop to get each value.