0

Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?

suppose we have an array like this:

var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';

ok? the Array is associated. and we have string key and string value. now! how can i pick a random value from that? Edit:i want to use like this:

<A href="Array value Here">Array Key Here</a>

Regards Sam

Community
  • 1
  • 1
G0back
  • 78
  • 2
  • 15
  • You're very confused about arrays in JavaScript. Arrays are always indexed and never associative. However, Arrays are just special objects and objects allow you to define keys just like you are doing in your code. See http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/ for more information. – Andy E Jul 10 '11 at 21:07
  • Thanks all,But I Want to pick Key and Value in same time. – G0back Jul 11 '11 at 05:00

2 Answers2

8

Using the method described here we can create the following function:

function randomKey(obj) {
    var ret;
    var c = 0;
    for (var key in obj)
        if (Math.random() < 1/++c)
           ret = key;
    return ret;
}

It returns a random key, so to get a random value from MrArray, do this:

var value = MrArray[randomKey(MrArray)];

jsPerf benchmark comparing the speed of this and the other answer.

Håvard
  • 9,900
  • 1
  • 41
  • 46
1

Here:

function fetch_random(obj) {
    var temp_key, keys = [];
    for(temp_key in obj) {
       if(obj.hasOwnProperty(temp_key)) {
           keys.push(temp_key);
       }
    }
    return obj[keys[Math.floor(Math.random() * keys.length)]];
}

Src: How can I choose an object key at random?

Community
  • 1
  • 1
Eddie
  • 12,898
  • 3
  • 25
  • 32