Get Random Number From Multidimensional Array
In a javascript function, I have a multidimension array as below. How can i get a random number from myObject[1]? var myObject= [ [ [2,3], [5,9], [4,7] ], [ [1,3], [5,8] ], [ [
Solution 1:
This could work:
var randomNumber = getRandom(myObject[1]);
functiongetRandom(arr) {
var random1 = Math.floor((Math.random() * (arr.length)));
return arr[random1][Math.floor((Math.random() * (arr[random1].length)))];
}
Solution 2:
Here is a recursive function that should do the trick
var multiDimNumberPicker = function(inputArray){
var randomItem;
//if item is an arrayif( Object.prototype.toString.call( inputArray ) === '[object Array]' ) {
//pick a random item to return
randomItem = inputArray[Math.floor(Math.random()*inputArray.length)];
console.log("is still array " + randomItem);
//process selected itemreturnmultiDimNumberPicker(randomItem);
}else{
console.log("not an array " + inputArray);
return inputArray;
}
};
//Generate a random number from myObject[1];var x = multiDimNumberPicker(myObject[1]);
console.log(x);
//Generate a random number from myObject;var y = multiDimNumberPicker(myObject);
console.log(y);
Example jsFiddle http://jsfiddle.net/rqk5m/1/
Post a Comment for "Get Random Number From Multidimensional Array"