Pick random Array from array of arrays in javascript
arrays, javascript, random
Solution
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.
- Polyfills are available.
- (MDN documentation)
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);
}
Problem
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?