Cures for the Common Ailments ' Getting a Random Item in JavaScript

At the end of the day yesterday one of my peers at my client came over and asked me how to randomly select an item from a SharePoint List. She was retrieving the list using jQuery and only wanted to display one item from the list, but she wanted that item to be random each time the page was loaded. She felt it would ultimately be the simplest solution to do this on the client, and I agreed. Our problem really came down to our personal limits using JavaScript, neither of us had done anything with random yet. I knew there had to be some pseudo-random number generator available, I have not met a modern language that does not have something to offer random yet.

Turns out JavaScript does have a random function that is a member of the Math object. I looked at a few uses of this function and decided using it with Math.floor() would produce the result we were after.

First, Math.random produces a 'random' value between 0 and 1. But we needed to randomly select an array item, which would be an integer index between 0 and the length '1. So multiplying the random result by the array's length will almost produce the index value desired. Passing the value to the Math.floor method will round the result down to the closest integer value. Now we have a 'random' integer value that can be reliably used to select an item from the array of items. The following code is an example of how to test this methodology:

<script type=

"text/javascript"

charset=

"utf-8"

>
$(document).ready(

function

() {

var

temp = [

'1'

,

'2'

,

'3'

,

'4'

,

'5'

,

'6'

];

$(

"#container"

).html((temp[get_random(temp.length)]));

});

function

get_random(max) {

if

(undefined === max) {
max = 5;
}

var

ranNum = Math.floor(Math.random() * max);

return

ranNum;
}
</script>

So back to the original problem. My co-worker is retrieving a SharePoint list from the web service APIs. This list should be represented as an array of object literals (assuming it is not a simple list of strings) in JavaScript. So instead of an array of strings she will be selecting an object literal and displaying values from that object. I am sorry I don't have a full blown demo of deserializing a SharePoint list, but if you refer to my recent post on using jQuery to communicate with WCF services you can see how to consume a list of objects in the example to retrieve a list of active contacts from the server.

Share This Article With Your Friends!