I have an array of arrays.
var ArrOfarr = { A1: ["choice", "choice2", "choice3"], A2: ["choice1", "choice2"], A3: ["choice1", "choice2"], A4: [], A5: [], A6: [], A7: [] }
I want to pick random array from the 'ArrOfarr' each time I click a button. I tried the below, but seeing 'undefined':
function A()
{
var item = ArrOfarr[Math.floor(Math.random()*ArrOfarr.length)];
alert(item);
}
how can I pick up random array form the above Array(Without repeat till it reaches its length). And how can I get the name of randomly picked array?
You do not have an array there, but an object containing arrays. To select a random entry, you could use this code:
function A(){
var keys = Object.keys( ArrOfarr );
var name = keys[ Math.floor(Math.random()*keys.length) ];
var item = ArrOfarr[ name ];
alert( name );
alert( item );
}
Object.keys()
is supported by most modern browsers. An alternative would be to change you data structure in the first place: Instead of arrays as inner object, you could use a wrapper object, that contains data
as well as name
.
var ArrOfarr = [ {name: 'A1', data: ["choice", "choice2", "choice3"] }, /* ... */ ];
function A() {
var item = ArrOfarr[Math.floor(Math.random()*ArrOfarr.length)];
alert(item.data);
}
var ArrOfarr = { A1: ["choice", "choice2", "choice3"], A2: ["choice1", "choice2"], A3: ["choice1", "choice2"], A4: [], A5: [], A6: [], A7: [] }
is a object literal
var ArrOfarr = [["choice", "choice2", "choice3"], ["choice1", "choice2"], ["choice1", "choice2"], [], [], [], []]
array of arrays;
Either change your code with array definition, or use Sirko's code instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With