Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random Array from array of arrays in javascript

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?

like image 876
M.K Avatar asked Feb 11 '14 09:02

M.K


2 Answers

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);
}
like image 122
Sirko Avatar answered Sep 29 '22 20:09

Sirko


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.

like image 27
Tudor Zgureanu Avatar answered Sep 29 '22 22:09

Tudor Zgureanu